代码:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController{ UISwitch *_switch; } - (void)viewDidLoad { [super viewDidLoad]; //创建开关(默认关状态) _switch = [[UISwitch alloc]initWithFrame:CGRectMake(0, 200, 100, 40)]; [self.view addSubview:_switch]; //添加事件switchChange [_switch addTarget:self action:@selector(switchChange) forControlEvents:UIControlEventValueChanged]; } - (void)switchChange{ if (_switch.isOn) { NSLog(@"开"); }else{ NSLog(@"关"); } }
// 控件大小,不能设置frame,只能用缩放比例
_switch.transform = CGAffineTransformMakeScale(0.8, 0.8);