改变背景颜色但为UISwitch保持色彩" On"州

时间:2018-01-23 14:54:47

标签: swift uiswitch

UISwitch位于" on"时,是否有任何方法可以在保持灰色边框的同时更改背景颜色状态?

通过设置:

switch.onTintColor = myGreen

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

enter image description here

2 个答案:

答案 0 :(得分:1)

斯威夫特3&斯威夫特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
}

答案 1 :(得分:1)

用灰色着色的区域将是交换机图层的borderColor。因此,通过执行以下操作,无论状态如何,边界仍将是相同的。

{
  "errors": [
    {
      "message": "Cannot query field \"test\" on type \"Group\".",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ]
    }
  ]
}

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

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)