Switch button Uiswitch
Inside the ViewController.h.
?
| 1234567891011121314151617 |
# Import <uikit/uikit.h> @interface viewcontroller:uiviewcontroller{ &NBSP;&NBSP; //define a switch control &NBSP;&NBSP; //function can be changed in state //on, off: two states can toggle //all controls in the Uikit framework library have UI start &NBSP;&NBSP; Code class= "CPP Comments" >//The official Apple controls are defined in the Uikit Framework library &NBSP;&NBSP; uiswitch * _myswitch; } @property (retain,nonatomic) Uiswitch * Myswitch; @end |
Inside the VIEWCONTROLLER.M.
?
| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 666768697071 |
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize mySwitch=_mySwitch;- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //创建一个开关对象 //继承于UIView的 _mySwitch = [[UISwitch alloc]init]; //苹果官方的控件的位置设置 //位置X,Y的值可以改变(100,100) //宽度和高度值无法改变(80,40)写了也没有用的,不会起到作用的。默认的。 _mySwitch.frame=CGRectMake(100, 200, 180, 40); //开关状态设置属性 //YES:开启状态 //NO:关闭状态 _mySwitch.on=YES; //也可以使用set函数 //[_mySwitch setOn:YES]; //设置开关状态 //p1:状态设置 //p2:是否开启动画效果 //[_mySwitch setOn:YES animated:YES]; [self.view addSubview:_mySwitch]; //设置开启状态的风格颜色 [_mySwitch setOnTintColor:[UIColor orangeColor]]; //设置开关圆按钮的风格颜色 [_mySwitch setThumbTintColor:[UIColor blueColor]]; //设置整体风格颜色,按钮的白色是整个父布局的背景颜色 [_mySwitch setTintColor:[UIColor greenColor]]; //向开关控件添加事件函数 //p1:函数实现对象 //p2:函数对象 //p3:事件响应时的事件类型UIControlEventValueChanged状态发生变化时触发函数 [_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];}//参数传入开关对象本身- (void) swChange:(UISwitch*) sw{ if(sw.on==YES){ NSLog(@"开关被打开"); }else{ NSLog(@"开关被关闭"); }}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end |
iOS switch button Uiswitch control