The first way to create a Uiswitch control is to create it dynamically in code.
1. Open Xcode 4.3.2, new project switch, select Single View application.
2. Open the Viewcontroller.m file to add code in the Viewdidload method:
-(void) viewdidload
{
[Super Viewdidload];
Uiswitch *switchbutton = [[Uiswitch alloc] Initwithframe:cgrectmake (50, 100, 20, 10)];
[Switchbutton Seton:yes];
[Switchbutton addtarget:self Action: @selector (switchaction:) forcontrolevents:uicontroleventvaluechanged];
[Self.view Addsubview:switchbutton];
Additional setup after loading the view, typically from a nib.
}
[Switchbutton addTarget:selfAction:@selector(switchaction:) forcontrolevents: Uicontroleventvaluechanged];
Switchaction in Selector in code: we need to do it ourselves, which is the event we receive when we press.
Remember to add the Switchbutton to the current view and call [self]. ViewAddsubview:switchbutton];
3, monitoring Uiswitch Press the event
The implementation code is as follows:
-(void) Switchaction: (ID) sender
{
Uiswitch *switchbutton = (uiswitch*) sender;
BOOL Isbuttonon = [Switchbutton isOn];
if (Isbuttonon) {
Showswitchvalue.text = @ "yes";
}else {
Showswitchvalue.text = @ "No";
}
}
Showswitchvalue is the label that I put on the interface by dragging the control method, which makes it easy to display the effect
Run, Effect:
Second, the use of uiswitch by drag-and-drop method
1. Drag a Uiswitch control to the Xib file.
2, press Alt+command + Return key to open Assistant editor mode, select the Uiswitch control, hold down the control key, drag to ViewController.h
3. Select action Mode
4. Switchaction is implemented in. m files. You can also use this method name when you create a dynamic, you may comment out just now.
-(Ibaction) Switchaction: (ID) Sender {
Uiswitch *switchbutton = (uiswitch*) sender;
BOOL Isbuttonon = [Switchbutton isOn];
if (Isbuttonon) {
Showswitchvalue.text = @ "yes";
}else {
Showswitchvalue.text = @ "No";
}
}
You can run it.
iOS Learning Uiswitch controls two ways to use and listen