更改背景颜色但保持 UISwitch "On" 状态的色调

Changing background colour but keeping tint for UISwitch "On" state

UISwitch 处于 "on" 状态时,有什么方法可以改变背景颜色同时保持灰色边框?

通过设置:

switch.onTintColor = myGreen

开关的边框也变成了绿色。但是在关闭状态下背景是透明的。

Swift 3 & Swift 4

//On viewDidLoad()
switch.addTarget(self, action: #selector(switch_Click), for: .valueChanged)

//add this func
@objc func switch_Click() {
    self.view.backgroundColor = (switch.isOn) ? UIColor.green : UIColor.orange
    self.switch.layer.borderColor = (switch.isOn) ? UIColor.lightGray.cgColor : UIColor.clear.cgColor
    self.switch.layer.borderWidth = 1.0
    self.switch.layer.cornerRadius = 16
}

灰色区域为开关图层的边框颜色。因此,通过执行以下操作,无论状态如何,边界仍然是相同的。

sender.layer.borderColor = UIColor.gray.cgColor // sender would be the switch if you where to change the color when the switch value has been changed 

默认情况下,您可以通过以下方式添加灰色层:

    let switcher = UISwitch()
    switcher.layer.masksToBounds = true
    switcher.layer.borderColor = UIColor.gray.cgColor // <-- we'll add the gray color
    switcher.layer.borderWidth = 2.0 // controll the width or thickness of the border
    switcher.layer.cornerRadius = 15 // from 15 and up you starting getting that round effect 
    switcher.frame = CGRect(x: 50, y: 100, width: 100, height: 40)
    switcher.addTarget(self , action: #selector(didPress), for: .valueChanged)

所以现在每次打开和关闭开关都可以改变颜色

@objc func didPress(sender: UISwitch) {
        switch sender.isOn {
        case true:
            sender.backgroundColor = .green
        case false:
            sender.backgroundColor = .orange
        }
    }