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