创建
UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-42, 10, 42, 24)];
switchButton.backgroundColor = [UIColor orangeColor];
[viewBG addSubview:switchButton];
设置属性
//设置开启颜色 图片
switchButton.onTintColor = [UIColor yellowColor];
switchButton.onImage = [UIImage imageNamed:@""];
//设置关闭颜色 图片
switchButton.tintColor = [UIColor redColor];
switchButton.offImage = [UIImage imageNamed:@""];
//设置圆形按钮颜色
switchButton.thumbTintColor = [UIColor purpleColor];
设置动画效果
//代码设置开启/关闭状态 设置YES或NO,是否使用animated动画效果:
[switchButton setOn:YES animated:YES];
设置开关状态
获取UISwitch的开闭状态 注:默认关闭
if (switchButton.isOn)
{
NSLog(@"开启状态");
}
else
{
NSLog(@"关闭状态");
}
添加动作事件
//添加动作事件
[switchButton addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
可以选择id类也可以选择UISwitch类,如果是id类型,则要转换成UISwitch类型:UISwitch *mySwitch = (UISwitch *)sender。
-(void)switchChange:(id)sender
{
UISwitch *mySwitch = (UISwitch *)sender;
if (mySwitch.isOn)
{
NSLog(@"开关开启");
}
else
{
NSLog(@"开关关闭");
}
}