Todos los objetos que se derivan de <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/cl/UIView">UIView</a> heredan las propiedades útiles <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW25">tag</a> Esta propiedad es un usuario real de datos (un "lugar" que el desarrollador utiliza para fines generales) del tipo <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/doc/c_ref/NSInteger">NSInteger</a> Entonces, ¿dónde podemos guardar sólo los números.
Los usos a los que, obviamente, puede depende de las circunstancias sin embargo, es útil para identificar un objeto en particular para tomar una ocurrencia común. Por ejemplo, imagine que tiene dos <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIAlertView_Class/UIAlertView/UIAlertView.html">UIAlertView</a> responder al mismo evento:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | / / Primero de alerta [ [ UIAlertView alloc ] initWithTitle : @ "Primo" message : @ "Primo Alert" delegate : self cancelButtonTitle : @ "OK" otherButtonTitles : nil , nil ] ; UIAlertView alerta * = [[UIAlertView alloc] initWithTitle: @ "Primera" mensaje: @ "First Alert" delegado: cancelButtonTitle auto: @ "OK" otherButtonTitles: nil, nil]; ; [Alerta show]; ; [Comunicado de alerta]; / / ... / / Alert Segunda [ [ UIAlertView alloc ] initWithTitle : @ "Secondo" message : @ "Secondo Alert" delegate : self cancelButtonTitle : @ "OK" otherButtonTitles : nil , nil ] ; UIAlertView alerta * = [[UIAlertView alloc] initWithTitle: @ "segundo" mensaje: @ "segunda alerta" delegado: cancelButtonTitle auto: @ "OK" otherButtonTitles: nil, nil]; ; [Alerta show]; ; [Comunicado de alerta]; / / Evento / / Cliccandi botón Aceptar de esta función será llamada de Alter void ) alertView : ( UIAlertView * ) alertView clickedButtonAtIndex : ( NSInteger ) buttonIndex { - (Void) alertView: (UIAlertView *) clickedButtonAtIndex alertView: (NSInteger) {buttonIndex / / Todo } |
Nota: ejemplos de código en C + + se encuentran las direcciones. Esto no es del todo correcto, ya que, como usted sabe, el lenguaje es Objective-C. Esto se debe al hecho de que los plugins que utilizo para ver el código fuente no es compatible con Objective-C y C + + es el que mejor se acerca a él.
¿Cómo diferenciar entre la alerta dos? Precisamente con la etiqueta de propiedad. Después de crear la alert simplemente escriba:
1 2 3 4 5 6 7 8 9 10 11 12 13 | / / Primero de alerta [ [ UIAlertView alloc ] initWithTitle : @ "Primo" message : @ "Primo Alert" delegate : self cancelButtonTitle : @ "OK" otherButtonTitles : nil , nil ] ; UIAlertView alerta * = [[UIAlertView alloc] initWithTitle: @ "Primera" mensaje: @ "First Alert" delegado: cancelButtonTitle auto: @ "OK" otherButtonTitles: nil, nil]; 1 ] ; // imposto il tag di questo Alert ad 1 [Ajuste de alerta: 1] / / establecer la etiqueta de esta Alerta en un ; [Alerta show]; ; [Comunicado de alerta]; / / ... / / Alert Segunda [ [ UIAlertView alloc ] initWithTitle : @ "Secondo" message : @ "Secondo Alert" delegate : self cancelButtonTitle : @ "OK" otherButtonTitles : nil , nil ] ; UIAlertView alerta * = [[UIAlertView alloc] initWithTitle: @ "segundo" mensaje: @ "segunda alerta" delegado: cancelButtonTitle auto: @ "OK" otherButtonTitles: nil, nil]; 2 ] ; // imposto il tag di questo Alert ad 2 [Ajuste de alerta: 2] / / establecer la etiqueta de esta Alerta a 2 ; [Alerta show]; ; [Comunicado de alerta]; |
Ahora modifique el evento con el fin de entender que una alerta se ha cerrado:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | / / Evento / / Cliccandi botón Aceptar de esta función será llamada de Alter void ) alertView : ( UIAlertView * ) alertView clickedButtonAtIndex : ( NSInteger ) buttonIndex { - (Void) alertView: (UIAlertView *) clickedButtonAtIndex alertView: (NSInteger) {buttonIndex alertView.tag ) { switch (alertView.tag) { : caso 1: / / First Alert break; : caso 2: / / Según alerta break; por defecto: break; } } |
Misma técnica se puede utilizar si tenemos una serie de <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html">UIButton</a> tiempo de ejecución. Por ejemplo:
1 2 3 4 5 6 7 8 9 10 | unsigned int i = 0 ; i < 10 ; i ++ ) { for (unsigned int i = 0; i <10; i + +) { [ [ UIButton buttonWithType : UIButtonTypeCustom ] initWithFrame : CGRectMake ( i * 20 , i * 20 , 20 , 20 ) ] ; UIButton * myButton = [[UIButton buttonWithType: UIButtonTypeCustom] initWithFrame: CGRectMake (i * 20, * 20, 20, 20)]; @ "But" forState : UIControlStateNormal ] ; [MyButton setTitle: @ "Pero", Forst: UIControlStateNormal]; i ] ; // imposto il tag [AJUSTE MyButton: i]; / / establecer la etiqueta / / El mismo evento para todos los self action : @selector ( onTouchUpInside : ) forControlEvents : UIControlEventTouchUpInside ] ; [AddTarget MyButton: acción de auto: @ selector (onTouchUpInside:) forControlEvents: UIControlEventTouchUpInside]; mybutton ] ; [Self.view addSubview: myButton]; } |
(dove eseguiamo un casting <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/cl/UIView">UIView</a> En el caso de onTouchUpInside recuperarse del sender (si llevamos a cabo un casting <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/cl/UIView">UIView</a> la propiedad <a target="_blank" href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW25">tag</a>
1 2 3 4 | void ) onTouchUpInside : ( id ) sender { - (Void) onTouchUpInside: (id) {remitente ( ( UIView * ) sender ) .tag; button_tag unsigned int = ((* UIView) remitente) etiquetas.; / / Todo } |










. Usted no debe abusar de la etiqueta de propiedades (obviamente este no es el caso) cuando se encuentran en situaciones donde la vista es la estructura de mucho, así que x subvista, ya que esta lista se mantiene con un
NSArray, este es escaneado con el fin de encontrar estatag.le
subview) Si la búsqueda se realiza mediante la comparación de los numéricostagde forma secuencial (y no creo que esto no se hace de otra manera, el máximo orden interno detagde lasubview)objectatindexno está muy bien, pero me puso por la sencillez de entender la semántica.2
3
4
5
self.subviews.objectatindex ( i ) .tag == tagrichiesto ) { if (self.subviews.objectatindex (s). tagrichiesto == tag) {
i ) ; self.subviews.objectatindex retorno (s);
}
}
1) en el mejor de los casos la
tages la primera, así que hicimos una comparación2) en un caso contra la mediana tenemos n
3) en el peor de los casos, no existe, se realizó para cada iteración de x contra la innecesaria
ipotizzando il caso peggiore del non trovato: avremo effettuato 100*10=1000 confronti inutili, per non parlare di invocazioni in cascata all'array subview e ai vari metodi di analisi). A menudo se utiliza para acceder a las celdas de la tabla, y en esta situación, donde tenemos cientos de filas con x
subviewpor línea que tiene la mayoría de los desechos (si usted es de 100 células de cada 10subviewsasumiendo el peor de los casos de que no se encuentra: que hace 100 * 10 = 1.000 comparaciones inútiles, por no hablar de la serie de invocaciones cascada subvista y los diversos métodos de análisis).visto che confrontiamo gli indirizzi fisici dei due oggetti (più veloce di così non si può). Me olvidé ... en algunas situaciones puede ser aconsejable usar un
iboutletsi usamos IB (Interface Builder) o un conjunto de propiedades asociadas con estos objetos, a los que puede acceder directamente desde cualquier método de nuestra clase, si la comparación es un objeto u otro en este caso puede hacerse simplemente mediante el operador==ya que se comparan las direcciones físicas de los dos objetos (más rápido de lo que no puede).per evitare di aggiungere variabili locali. En el ejemplo mostrado está muy bien, por supuesto, con el tiempo haciendo una comparación entre "todo" en el
switch, pero he visto utilizar muchas / abuso de lastagpara evitar la adición de variables locales.una buena planificación