1.初始化UISwitch到界面
UISwitch* newsSwitch = [[UISwitch alloc]init];
cell.accessoryView= newsSwitch;
2.默认开启
[newsSwitch setOn:YES animated:YES];
3.自定义UI
// 开关开启时的颜色(默认绿色)
newsSwitch.onTintColor= [UIColor redColor];
// 开关圆圈的颜色(默认白色)
newsSwitch.thumbTintColor= [UIColor redColor];
// 开关关闭时的边框颜色(默认白色)
newsSwitch.tintColor= [UIColor redColor];
4.添加开关的监听事件
[newsSwitch addTarget:self action:@selector(switchChange:)forControlEvents:UIControlEventValueChanged];
- (void) switchChange:(UISwitch*)sender {
if([sender isOn]){
NSLog(@"turn on");
}else{
NSLog(@"turned off");
}
}