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

标签 swift uiswitch

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

通过设置:

switch.onTintColor = myGreen

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

enter image description here

最佳答案

用灰色着色的区域将是开关层的 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/

相关文章:

sorting - 使用有序数组对字典进行排序

iphone - 另一个自定义 UISwitch 问题

ios - 在 NSUserDefaults 中保存自定义 NSObject

ios - UIDocumentInteractionController 在不保存 Swift 的情况下使用来自 Web 的 URL 打开

swift - 事件工具包授权错误。 [命令行工具]

ios - switch in a tableview with UserDefaults, several is activated by itself

ios - "On"UISwitch 的状态

ios - xCode 4.2 将 UISwitch 分配给一个部分的一行会产生奇怪的行为...... IOS

android-studio - 如何单击单击后具有其自己的StatelessWidget类的开关?

ios - 查询解析表中的所有数据并放入数组中