Apple iPhone: creare un custom toggle button

Gli stati UIControlStateSelected o UIControlStateHighlighted non funzionano quando un UIButton è impostato in modalità UIButtonTypeCustom! O meglio, non funzionano come dovrebbero (perchè riservati agli altri tipi di bottone), ad esempio per creare un bottone a due stati: toggle appunto. Se abbiamo creato due immagini (stato1.png e stato2.png) per il nostro bottone, possiamo procedere in questo modo:

1
2
3
// Nell'header file creiamo una variabile globale che usaremo per
// controllare il toggle state
BOOL toggleFlag;

Ora creiamo il nostro bottone:

1
2
3
4
5
6
7
8
9
// Creaiamo un bottone e lo poniamo inizialmente nello stato "stato1.png"
// Modificate initWithFrame:(CGRect){100,100,50,50} con la posizione e
// dimensioni della vostra immmagine
toggleFlag = YES;
UIButton *toggleButton = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:(CGRect){100,100,50,50}];
[toggleButton setTitle:@"" forState:UIControlStateNormal];
[toggleButton setBackgroundImage:[UIImage imageNamed:@"stato1.png"] forState:UIControlStateNormal];
[toggleButton addTarget:self action:@selector(onToggle:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:toggleButton];

Quando si clicca sul bottone verrà inviato un messaggio gestito da onToggle:

1
2
3
4
5
6
7
- (void)onToggle:(id)sender {
// Recupero puntatore al UIButton
UIButton *buttonClicked = (UIButton *)sender;
// Eseguo il toogle
toggleFlag = !toggleFlag;
[buttonClicked setBackgroundImage:[UIImage imageNamed:(toggleFlag) ? @"stato1.png" : @"stato2.png"] forState:UIControlStateNormal];
}

Non ci sono commenti per questo Post

Lascia un commento

TAG XHTML PERMESSI: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERIMENTO CODICE:
<pre></pre> // blocco generico
                   <code></code> // blocco generico
                   [cc_actionscript][/cc_actionscript] // Actionscript
                   [cc_actionscript3][/cc_actionscript3] // Actionscript 3
                   [cc_css][/cc_css] // CSS Style Sheet
                   [cc_html][/cc_html] // HTML
                   [cc_js][/cc_js] // Javascript
                   [cc_objc][/cc_objc] // Objective-C
                   [cc_php][/cc_objc] // PHP
                   [cc_sql][/cc_sql] // SQL