自定义UISwitch颜色

秦禄
2023-12-01

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, 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)")
}
 类似资料: