将UISwitch的颜色更改为“closures”状态

我已经了解到,我们可以将UISwitchbutton的外观改为“on”状态,但是也可以在“off”状态下改变UISwitch的颜色吗?

尝试使用这个

yourSwitch.backgroundColor = [UIColor whiteColor]; youSwitch.layer.cornerRadius = 16.0; 

感谢@Barry Wyckoff。

我的解决scheme#swift2:

 let onColor = _your_on_state_color let offColor = _your_off_state_color let mSwitch = UISwitch(frame: CGRectZero) mSwitch.on = true /*For on state*/ mSwitch.onTintColor = onColor /*For off state*/ mSwitch.tintColor = offColor mSwitch.layer.cornerRadius = 16 mSwitch.backgroundColor = offColor 

结果:

在这里输入图像说明

您可以在交换机上使用tintColor属性。

 switch.tintColor = [UIColor redColor]; // the "off" color switch.onTintColor = [UIColor greenColor]; // the "on" color 

请注意,这需要iOS 5+

Swift IBDesignable

 import UIKit @IBDesignable class UISwitchCustom: UISwitch { @IBInspectable var OffTint: UIColor? { didSet { self.tintColor = OffTint self.layer.cornerRadius = 16 self.backgroundColor = OffTint } } } 

在身份检查器中设置类

在这里输入图像说明

改变属性检查器的颜色

在这里输入图像说明

产量

在这里输入图像说明

pipe理UISwitch背景颜色和大小的最佳方法

现在是Swift 2.3代码

 import Foundation import UIKit @IBDesignable class UICustomSwitch : UISwitch { @IBInspectable var OnColor : UIColor! = UIColor.blueColor() @IBInspectable var OffColor : UIColor! = UIColor.grayColor() @IBInspectable var Scale : CGFloat! = 1.0 override init(frame: CGRect) { super.init(frame: frame) self.setUpCustomUserInterface() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUpCustomUserInterface() } func setUpCustomUserInterface() { //clip the background color self.layer.cornerRadius = 16 self.layer.masksToBounds = true //Scale down to make it smaller in look self.transform = CGAffineTransformMakeScale(self.Scale, self.Scale); //add target to get user interation to update user-interface accordingly self.addTarget(self, action: #selector(UICustomSwitch.updateUI), forControlEvents: UIControlEvents.ValueChanged) //set onTintColor : is necessary to make it colored self.onTintColor = self.OnColor //setup to initial state self.updateUI() } //to track programatic update override func setOn(on: Bool, animated: Bool) { super.setOn(on, animated: true) updateUI() } //Update user-interface according to on/off state func updateUI() { if self.on == true { self.backgroundColor = self.OnColor } else { self.backgroundColor = self.OffColor } } } 

使用代码或故事板的项目中的任何UISlider上使用的目标c类别:

 #import <UIKit/UIKit.h> @interface UISwitch (SAHelper) @property (nonatomic) IBInspectable UIColor *offTint; @end 

履行

 #import "UISwitch+SAHelper.h" @implementation UISwitch (SAHelper) @dynamic offTint; - (void)setOffTint:(UIColor *)offTint { self.tintColor = offTint; //comment this line to hide border in off state self.layer.cornerRadius = 16; self.backgroundColor = offTint; } @end 

为了获得更好的色彩performanceforms,我们只允许在“开启”状态下显示一种色彩。

在色调上:

在这里输入图像说明

closures色调:

在这里输入图像说明

设置默认色调:

在这里输入图像说明