Apple iPhone: Create a custom toggle button

non funzionano quando un UIButton è impostato in modalità UIButtonTypeCustom ! The states UIControlStateSelected or UIControlStateHighlighted do not work when a UIButton is set in mode UIButtonTypeCustom ! Or rather, do not work (because reserved for other types of button), for example to create a button with two states: toggle note. If we have created two images (stato1.png and stato2.png) for our button, we can proceed as follows:

1
2
3
/ / The header file that we create a global variable for usaremo
/ / Toggle the check was
BOOL toggleFlag;

Now we create our button:

1
2
3
4
5
6
7
8
9
/ / We create a button and we place it initially in the state "stato1.png"
/ / Edit initWithFrame: (CGRect) {100,100,50,50} with the position and
/ / Size of your image has
; toggleFlag = YES;
[ [ UIButton buttonWithType : UIButtonTypeCustom ] initWithFrame : ( CGRect ) { 100 , 100 , 50 , 50 } ] ; UIButton * ToggleButton = [[UIButton buttonWithType: UIButtonTypeCustom] initWithFrame: (CGRect) {100, 100, 50, 50}];
@ "" forState : UIControlStateNormal ] ; [ToggleButton setTitle: @ "" forState: UIControlStateNormal];
[ UIImage imageNamed : @ "stato1.png" ] forState : UIControlStateNormal ] ; [ToggleButton setBackgroundImage: [UIImage imageNamed: @ "stato1.png"] forState: UIControlStateNormal];
self action : @selector ( onToggle : ) forControlEvents : UIControlEventTouchUpInside ] ; [ToggleButton AddTarget: self action: @ selector (onToggle:) forControlEvents: UIControlEventTouchUpInside];
toggleButton ] ; [Self.view addSubview: ToggleButton];

When you click on the button will send a message to be managed onToggle :

1
2
3
4
5
6
7
void ) onToggle : ( id ) sender { - (Void) onToggle: (id) sender {
/ / Retrieve pointer to UIButton
( UIButton * ) sender; UIButton ButtonClicked * = (UIButton *) sender;
/ / Executing the Toogle
toggleFlag =! toggleFlag;
[ UIImage imageNamed : ( toggleFlag ) ? @ "stato1.png" : @ "stato2.png" ] forState : UIControlStateNormal ] ; [ButtonClicked setBackgroundImage: [UIImage imageNamed: (toggleFlag)? @ "Stato1.png" @ "stato2.png"] forState: UIControlStateNormal];
}

There are no comments for this post

Leave a comment

TAG XHTML PERMITS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <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 


Stop SOPA