当 UISwitch
处于“on”状态时,有什么方法可以改变背景颜色同时保持灰色边框吗?
通过设置:
switch.onTintColor = myGreen
开关的边框也变为绿色。但在关闭状态下,背景是透明的。
最佳答案
用灰色着色的区域将是开关层的 borderColor。因此,通过执行以下操作,无论状态如何,边界仍然是相同的。
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
}
}
关于swift - 更改背景颜色但保持 UISwitch "On"状态的色调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404617/