Change color of UISwitch in “off” state

前端 未结 18 2714
忘掉有多难
忘掉有多难 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条回答
  •  -上瘾入骨i
    2020-11-30 21:49

    2020 As of Xcode 11.3.1 & Swift 5

    Here's the simplest way I've found of doing setting the UISwitch off-state colour with one line of code. Writing this here since this page is what came up first when I was looking and the other answers didn't help.

    This is if I wanted to set the off state to be red, and can be added to the viewDidLoad() function:

    yourSwitchName.subviews[0].subviews[0].backgroundColor = UIColor.red
    

    Note - what this is actually doing is setting the background colour of the switch. This may influence the colour of the switch in the on-state too (though for me this wasn't a problem since I wanted the on and off state to be the same colour).

    A solution for this:

    Simply tie in the colours with an 'if else' statement inside your IBAction. If the switch is off, colour the background red. If the switch is on, leave the background clear so your chosen 'on' colour will display properly.

    This goes inside the switch IBAction.

      if yourSwitch.isOn == false {
               yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
        } else {
            yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.clear
        }
    

    I found some behaviour where, upon the app resuming from background, the switch background would return to clear. To remedy this problem I simply added in the following code to set the colour every time the app comes to the foreground:

     override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        NotificationCenter.default.addObserver(
          self,
          selector: #selector(applicationWillEnterForeground(_:)),
          name: UIApplication.willEnterForegroundNotification,
          object: nil)
    }
    
    @objc func applicationWillEnterForeground(_ notification: NSNotification) {
       yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
       yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
    }
    

    Seems simpler than the other answers. Hope that helps!

提交回复
热议问题