自定义UISwitch颜色

前端之家收集整理的这篇文章主要介绍了自定义UISwitch颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

UISwithch属性说明:

  1. tintColor:开关处于关闭状态时的颜色
  2. onTintColor:开关处于开启状态时的颜色
  3. thumbTintColor:开关的状态钮颜色
  4. onImage:开关处于开启状态时的图片(iOS7及之后设置无效)
  5. offImage:开关处于关闭状态时的图片(iOS7及之后设置无效)
  6. 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)")
}
原文链接:https://www.f2er.com/swift/325686.html

猜你在找的Swift相关文章