Change color of UISwitch in “off” state

前端 未结 18 2721
忘掉有多难
忘掉有多难 2020-11-30 20:53

I\'ve learned that we can change the UISwitch button appearance in its \"on\" state, but is it also possible to change the color of the UISwitch in the \"off\" state?

18条回答
  •  失恋的感觉
    2020-11-30 21:33

    Should you need other switches around your app, it might be also a good idea implementing @LongPham's code inside a custom class. As others have pointed out, for the "off" state you'll need to change the background colour as well, since the default is transparent.

    class MySwitch: UISwitch {
    
      required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    
        // Setting "on" state colour
        self.onTintColor        = UIColor.green
    
        // Setting "off" state colour
        self.tintColor          = UIColor.red
        self.layer.cornerRadius = self.frame.height / 2
        self.backgroundColor    = UIColor.red
      }
    }
    

提交回复
热议问题