UISwithch属性说明:
tintColor
:开关处于关闭状态时的颜色onTintColor
:开关处于开启状态时的颜色thumbTintColor
:开关的状态钮颜色onImage
:开关处于开启状态时的图片(iOS7及之后设置无效)offImage
:开关处于关闭状态时的图片(iOS7及之后设置无效)backgroundColor
:整个开关背景色,设置后可以明显看到一个矩形背景
iOS系统内置了UISwithch控件的size,所以通过代码调整UISwithch的大小无效.
oc代码:
- (void)viewDidLoad { [super viewDidLoad]; self.mSwitch.tintColor = [UIColor redColor]; self.mSwitch.onTintColor = [UIColor blackColor]; self.mSwitch.thumbTintColor = [UIColor yellowColor]; self.mSwitch.backgroundColor = [UIColor purpleColor]; //iOS7&later设置无效 self.mSwitch.onImage = [UIImage imageNamed:@"on"]; self.mSwitch.offImage = [UIImage imageNamed:@"off"]; //设置无效 UISwitch *s = [[UISwitch alloc]initWithFrame:CGRectMake(100,100,200,200)]; [self.view addSubview:s]; } - (IBAction)switchValueDidChanged:(UISwitch *)sender { NSLog(@"%@",sender.isOn?@"switch is On":@"switch is Off"); }
swift代码:
@IBOutlet weak var mSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() self.mSwitch.tintColor = UIColor.redColor() self.mSwitch.onTintColor = UIColor .yellowColor() self.mSwitch.thumbTintColor = UIColor.blueColor() self.mSwitch.backgroundColor = UIColor.clearColor() var sw = UISwitch(frame: CGRectMake(0,0)) sw.addTarget(self,action: "switchValueDidChanged",forControlEvents: UIControlEvents.ValueChanged) self.view.addSubview(sw) } @IBAction func switchValueDidChanged(sender: UISwitch) { var result = sender.on ? "on" : "off" println("switch is \(result)") }