【问题标题】:Changing background colour but keeping tint for UISwitch "On" state更改背景颜色但保持 UISwitch“开”状态的色调
【发布时间】:2018-07-02 10:39:15
【问题描述】:

UISwitch 处于“开启”状态时,有什么方法可以在保持灰色边框的同时更改背景颜色?

通过设置:

switch.onTintColor = myGreen

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

【问题讨论】:

    标签: swift uiswitch


    【解决方案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
    }
    

    【讨论】:

      【解决方案2】:

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

      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
              }
          }
      

      【讨论】:

      • 谢谢,它几乎解决了我的问题。唯一的问题是在 on 状态下将 backgroundColor 设置为 .green 没有任何作用。相反,将 onTintColor 设置为 .green 就可以了。
      猜你喜欢
      • 1970-01-01
      • 2015-09-26
      • 2019-11-20
      • 2016-10-16
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      相关资源
      最近更新 更多