119

我了解到我们可以在“on”状态下更改 UISwitch 按钮的外观,但是否也可以在“off”状态下更改 UISwitch 的颜色?

4

19 回答 19

172

我使用#swift2 的解决方案:

let onColor  = _your_on_state_color
let offColor = _your_off_state_color

let mSwitch = UISwitch(frame: CGRect.zero)
mSwitch.on = true

/*For on state*/
mSwitch.onTintColor = onColor

/*For off state*/
mSwitch.tintColor = offColor
mSwitch.layer.cornerRadius = mSwitch.frame.height / 2.0
mSwitch.backgroundColor = offColor
mSwitch.clipsToBounds = true

结果:

在此处输入图像描述

于 2015-10-07T08:58:58.493 回答
140

尝试使用这个

yourSwitch.backgroundColor = [UIColor whiteColor];
youSwitch.layer.cornerRadius = 16.0;

感谢@Barry Wyckoff。

于 2014-04-03T06:56:10.983 回答
44

您可以使用tintColor交换机上的属性。

switch.tintColor = [UIColor redColor]; // the "off" color
switch.onTintColor = [UIColor greenColor]; // the "on" color

请注意,这需要 iOS 5+

于 2013-10-01T18:11:24.310 回答
29

Swift IBDesignable

import UIKit
@IBDesignable

class UISwitchCustom: UISwitch {
    @IBInspectable var OffTint: UIColor? {
        didSet {
            self.tintColor = OffTint
            self.layer.cornerRadius = 16
            self.backgroundColor = OffTint
        }
    }
}

在身份检查器中设置类

在此处输入图像描述

从属性检查器更改颜色

在此处输入图像描述

输出

在此处输入图像描述

于 2016-08-03T07:18:06.883 回答
20

这是一个非常好的技巧:您可以直接进入 UISwitch 的子视图,该子视图绘制其“关闭”背景,并更改其背景颜色。这在 iOS 13 中比在 iOS 12 中效果更好:

if #available(iOS 13.0, *) {
    self.sw.subviews.first?.subviews.first?.backgroundColor = .green
} else if #available(iOS 12.0, *) {
    self.sw.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .green
}
于 2019-09-28T01:38:27.407 回答
8

管理 UISwitch 背景颜色和大小的最佳方法

现在是 Swift 2.3 代码

import Foundation
import UIKit

@IBDesignable
class UICustomSwitch : UISwitch {

    @IBInspectable var OnColor : UIColor! = UIColor.blueColor()
    @IBInspectable var OffColor : UIColor! = UIColor.grayColor()
    @IBInspectable var Scale : CGFloat! = 1.0

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUpCustomUserInterface()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setUpCustomUserInterface()
    }


    func setUpCustomUserInterface() {

        //clip the background color
        self.layer.cornerRadius = 16
        self.layer.masksToBounds = true

        //Scale down to make it smaller in look
        self.transform = CGAffineTransformMakeScale(self.Scale, self.Scale);

        //add target to get user interation to update user-interface accordingly
        self.addTarget(self, action: #selector(UICustomSwitch.updateUI), forControlEvents: UIControlEvents.ValueChanged)

        //set onTintColor : is necessary to make it colored
        self.onTintColor = self.OnColor

        //setup to initial state
        self.updateUI()
    }

    //to track programatic update
    override func setOn(on: Bool, animated: Bool) {
        super.setOn(on, animated: true)
        updateUI()
    }

    //Update user-interface according to on/off state
    func updateUI() {
        if self.on == true {
            self.backgroundColor = self.OnColor
        }
        else {
            self.backgroundColor = self.OffColor
        }
    }
}
于 2017-05-10T09:34:35.183 回答
7

在此处输入图像描述
在此处输入图像描述
工作 100% IOS 13.0 和 Swift 5.0 切换两个状态颜色设置相同#ios13 #swift #swift5

@IBOutlet weak var switchProfile: UISwitch!{
    didSet{
        switchProfile.onTintColor = .red
        switchProfile.tintColor = .red
        switchProfile.subviews[0].subviews[0].backgroundColor = .red
    }
}
于 2020-06-26T07:26:42.583 回答
6

斯威夫特 5:

import UIKit

extension UISwitch {    

    func set(offTint color: UIColor ) {
        let minSide = min(bounds.size.height, bounds.size.width)
        layer.cornerRadius = minSide / 2
        backgroundColor = color
        tintColor = color
    }
}
于 2019-03-28T11:27:55.817 回答
6

如果您需要围绕您的应用程序进行其他切换,那么在自定义类中实现@LongPham 的代码也是一个好主意。正如其他人指出的那样,对于“关闭”状态,您还需要更改背景颜色,因为默认设置是透明的。

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
  }
}
于 2019-07-15T02:56:49.190 回答
4

在 Swift 4+ 中:

off状态:

switch.tintColor = UIColor.blue

on状态:

switch.onTintColor = UIColor.red
于 2018-09-24T11:40:19.317 回答
4

Swift 4最简单快捷的方式,只需 3 步即可:

// background color is the color of the background of the switch
switchControl.backgroundColor = UIColor.white.withAlphaComponent(0.9)

// tint color is the color of the border when the switch is off, use
// clear if you want it the same as the background, or different otherwise
switchControl.tintColor = UIColor.clear

// and make sure that the background color will stay in border of the switch
switchControl.layer.cornerRadius = switchControl.bounds.height / 2

如果您手动更改开关的大小(例如,通过使用自动布局),您也必须更新开关switch.layer.cornerRadius,例如,通过覆盖layoutSubviews并在调用 super 更新角半径之后:

override func layoutSubviews() {
    super.layoutSubviews()
    switchControl.layer.cornerRadius = switchControl.bounds.height / 2
}
于 2018-02-23T12:30:55.633 回答
3

UISwitchoffTintColor是透明的,因此开关后面的任何内容都会显示出来。因此,与其掩盖背景颜色,不如在开关后面绘制一个开关形状的图像就足够了(这个实现假设开关是通过自动布局定位的):

func putColor(_ color: UIColor, behindSwitch sw: UISwitch) {
    guard sw.superview != nil else {return}
    let onswitch = UISwitch()
    onswitch.isOn = true
    let r = UIGraphicsImageRenderer(bounds:sw.bounds)
    let im = r.image { ctx in
        onswitch.layer.render(in: ctx.cgContext)
        }.withRenderingMode(.alwaysTemplate)
    let iv = UIImageView(image:im)
    iv.tintColor = color
    sw.superview!.insertSubview(iv, belowSubview: sw)
    iv.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        iv.topAnchor.constraint(equalTo: sw.topAnchor),
        iv.bottomAnchor.constraint(equalTo: sw.bottomAnchor),
        iv.leadingAnchor.constraint(equalTo: sw.leadingAnchor),
        iv.trailingAnchor.constraint(equalTo: sw.trailingAnchor),
    ])
}

[但现在看看我的另一个答案。]

于 2018-07-29T13:16:52.697 回答
3

2020 从 Xcode 11.3.1 和 Swift 5 开始

这是我发现的用一行代码设置 UISwitch 关闭状态颜色的最简单方法。在这里写这个,因为这个页面是我在寻找时首先出现的,而其他答案没有帮助。

这是如果我想将关闭状态设置为红色,并且可以添加到 viewDidLoad() 函数中:

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

注意 - 这实际上是在设置开关的背景颜色。这也可能会影响开启状态下开关的颜色(尽管对我来说这不是问题,因为我希望开启和关闭状态是相同的颜色)。

解决方案:

只需将颜色与 IBAction 中的“if else”语句联系起来即可。如果开关关闭,则将背景涂成红色。如果开关打开,请保持背景清晰,以便您选择的“打开”颜色正确显示。

这进入开关 IBAction内部。

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

我发现了一些行为,当应用程序从后台恢复时,切换背景会恢复为清除状态。为了解决这个问题,我简单地添加了以下代码来设置应用程序每次进入前台时的颜色:

 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
}

似乎比其他答案更简单。希望有帮助!

于 2020-02-09T23:28:52.687 回答
2

我在 IOS 14 上进行了测试,将背景设置为关闭颜色并将 onTintColor 设置为打开并且可以正常工作:

uiSwitch.onTintColor = UIColor.blue
uiSwitch.backgroundColor = UIColor.red
于 2021-05-01T12:29:44.313 回答
1

XCode 11,斯威夫特 5

我不喜欢使用子视图,因为你永远不知道苹果什么时候会改变层次结构。

所以我改用遮罩视图。

它适用于 iOS 12、iOS 13

    private lazy var settingSwitch: UISwitch = {
        let swt: UISwitch = UISwitch()
        // set border color when isOn is false
        swt.tintColor = .cloudyBlueTwo
        // set border color when isOn is true
        swt.onTintColor = .greenishTeal

        // set background color when isOn is false
        swt.backgroundColor = .cloudyBlueTwo

        // create a mask view to clip background over the size you expected.
        let maskView = UIView(frame: swt.frame)
        maskView.backgroundColor = .red
        maskView.layer.cornerRadius = swt.frame.height / 2
        maskView.clipsToBounds = true
        swt.mask = maskView

        // set the scale to your expectation, here is around height: 34, width: 21.
        let scale: CGFloat = 2 / 3
        swt.transform = CGAffineTransform(scaleX: scale, y: scale)
        swt.addTarget(self, action: #selector(switchOnChange(_:)), for: .valueChanged)
        return swt
    }()

    @objc
    func switchOnChange(_ sender: UISwitch) {
        if sender.isOn {
            // set background color when isOn is true
            sender.backgroundColor = .greenishTeal
        } else {
            // set background color when isOn is false
            sender.backgroundColor = .cloudyBlueTwo
        }
    }

于 2020-04-06T13:02:25.547 回答
1

Swift 3中更安全的方法,没有神奇的 16pt 值:

class ColoredBackgroundSwitch: UISwitch {

  var offTintColor: UIColor {
    get {
      return backgroundColor ?? UIColor.clear
    }
    set {
      backgroundColor = newValue
    }
  }

  override func layoutSubviews() {
    super.layoutSubviews()
    let minSide = min(frame.size.height, frame.size.width)
    layer.cornerRadius = ceil(minSide / 2)
  }

}
于 2017-12-27T10:30:14.627 回答
1

使用代码或故事板在项目中的任何 UISwitch 上使用的目标 c 类别:

#import <UIKit/UIKit.h>

@interface UISwitch (SAHelper)
@property (nonatomic) IBInspectable UIColor *offTint;
@end

执行

#import "UISwitch+SAHelper.h"

@implementation UISwitch (SAHelper)
@dynamic offTint;
- (void)setOffTint:(UIColor *)offTint {
    self.tintColor = offTint;   //comment this line to hide border in off state
    self.layer.cornerRadius = 16;
    self.backgroundColor = offTint;
}
@end
于 2016-10-12T13:47:26.037 回答
0

我最终也使用了 transform 和 layer.cornerRadius 。但我已将翻译添加到它的中心。

    private func setSwitchSize() {
    let iosSwitchSize = switchBlockAction.bounds.size
    let requiredSwitchSize = ...
    let transform = CGAffineTransform(a: requiredSwitchSize.width / iosSwitchSize.width, b: 0,
                                      c: 0, d:  requiredSwitchSize.height / iosSwitchSize.height,
                                      tx: (requiredSwitchSize.width - iosSwitchSize.width) / 2.0,
                                      ty: (requiredSwitchSize.height - iosSwitchSize.height) / 2.0)

    switchBlockAction.layer.cornerRadius = iosSwitchSize.height / 2.0
    switchBlockAction.transform = transform
}

我确实在设计器中使用了 backgroundColor 和 tintColor。希望能帮助到你。

于 2020-04-23T12:56:56.483 回答
0

XCode 11,斯威夫特 4.2

Matt 的解决方案开始,我将它添加到自定义的 IBDesignable 控件中。在需要处理didMoveToSuperview()的设置之前调用存在时间问题。offTintColor

@IBDesignable public class UISwitchCustom: UISwitch {

    var switchMask: UIImageView?
    private var observers = [NSKeyValueObservation]()

    @IBInspectable dynamic var offTintColor : UIColor! = UIColor.gray {
        didSet {
             switchMask?.tintColor = offTintColor
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeObservers()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeObservers()
    }

    private func initializeObservers() {
        observers.append(observe(\.isHidden, options: [.initial]) {(model, change) in
            self.switchMask?.isHidden = self.isHidden
        })
    }

    override public func didMoveToSuperview() {
        addOffColorMask(offTintColor)
        super.didMoveToSuperview()
    }

   private func addOffColorMask(_ color: UIColor) {
        guard self.superview != nil else {return}
        let onswitch = UISwitch()
        onswitch.isOn = true
        let r = UIGraphicsImageRenderer(bounds:self.bounds)
        let im = r.image { ctx in
            onswitch.layer.render(in: ctx.cgContext)
            }.withRenderingMode(.alwaysTemplate)
        let iv = UIImageView(image:im)
        iv.tintColor = color
        self.superview!.insertSubview(iv, belowSubview: self)
        iv.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            iv.topAnchor.constraint(equalTo: self.topAnchor),
            iv.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            iv.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            iv.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            ])
        switchMask = iv
        switchMask?.isHidden = self.isHidden
    }

}
于 2019-01-31T20:54:27.103 回答