Just as the segment control replaces the single button, the switch also replaces the click box. The switch is the simplest control used so far, but it can still be customized to a certain extent.
I. Create
Uiswitch * myswitch = [[uiswitch alloc] initwithframe: cgrectmake (200.0, 10.0, 0.0, 0.0)];
Isn't it strange that the size turns out to be 0.0 × 0.0? Yes, the system will automatically help you decide the optimal size, and the size you write will be ignored, you only need to define the location of the parent view. About pureCodeFor details about how to create a widget, see my other blog:Several Basic knowledge points about View
Ii. display controls
[Parrentview addsubview: myswitch]; // Add to parent View
Or
Self. navigationitem. titleview = myswitch; // Add to navigation bar
Ii. Switch Status
The switch status can be read through its on attribute. This attribute is a bool value, indicating whether the switch is Enabled:
Bool switchstatus = myswitch. on;
You can use the Seton method in your code to turn on or off the switch:
[Myswitch Seton: Yes animated: Yes];
3. Notifications
To receive a notification when switching the switch status, you can use the addtarget method of the uicontrol class to add an action for the uicontroleventvaluechanged event.
[Myswitch addtarget: Self action: @ selector (switchvaluechanged :) forcontrolevents: uicontroleventvaluechanged];
In this way, as soon as the switch is switched to the target class (in the previous example, the target class is the current controller self), The switchvaluechanged method will be called. Is it great?
-(Void) switchvaluechanged :( ID) sender {uiswitch * control = (uiswitch *) sender; If (control = myswitch) {bool on = control. on; // Add the code for the task you want to handle }}
After learning about the switch, do you think it is great? Is there a lot of places to use it? If you think it's good, just write some code and try it!