ios 在“关闭”状态下更改 UISwitch 的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10348869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:07:50  来源:igfitidea点击:

Change color of UISwitch in "off" state

iphoneiosuiswitch

提问by user198725878

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?

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

回答by Sourabh Bhardwaj

Try using this

尝试使用这个

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

All thanks to @Barry Wyckoff.

感谢@Barry Wyckoff。

回答by Long Pham

My solution with #swift2:

我的#swift2 解决方案:

let onColor  = _your_on_state_color
let offColor = _your_off_state_color

let mSwitch = UISwitch(frame: CGRectZero)
mSwitch.on = true

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

/*For off state*/
mSwitch.tintColor = offColor
mSwitch.layer.cornerRadius = mSwitch.frame.height / 2
mSwitch.backgroundColor = offColor

Result:

结果:

enter image description here

在此处输入图片说明

回答by bengoesboom

You can use the tintColorproperty on the switch.

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

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

Note this requires iOS 5+

请注意,这需要 iOS 5+

回答by Afzaal Ahmad

Swift IBDesignable

Swift IBDesignable

import UIKit
@IBDesignable

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

set class in Identity inspector

在身份检查器中设置类

enter image description here

在此处输入图片说明

change color from Attributes inspector

从属性检查器更改颜色

enter image description here

在此处输入图片说明

Output

输出

enter image description here

在此处输入图片说明

回答by matt

Here's a pretty good trick: you can just reach right into the UISwitch's subview that draws its "off" background, and change its background color. This works a lot better in iOS 13 than it does in iOS 12:

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

if #available(iOS 13.0, *) {
    self.sw.subviews[0].subviews[0].backgroundColor = .green
} else if #available(iOS 12.0, *) {
    self.sw.subviews[0].subviews[0].subviews[0].backgroundColor = .green
}

回答by kalpesh jetani

The Best way to manage background color & size of UISwitch

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

For now it's Swift 2.3 code

现在是 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
        }
    }
}

回答by Chryb

In Swift 4+:

在 Swift 4+ 中:

offstate:

off状态:

switch.tintColor = UIColor.blue

onstate:

on状态:

switch.onTintColor = UIColor.red

回答by Ivan

Swift 5:

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

回答by Milan Nosá?

Swift 4easiest and fastest way to get it in 3 steps:

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

If you manually change the size of the switch (e.g., by using autolayout), you will have to update the switch.layer.cornerRadiustoo, e.g., by overriding layoutSubviewsand after calling super updating the corner radius:

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

override func layoutSubviews() {
    super.layoutSubviews()
    switchControl.layer.cornerRadius = switchControl.bounds.height / 2
}

回答by matt

The UISwitch offTintColoris transparent, so whatever is behind the switch shows through. Therefore, instead of masking the background color, it suffices to draw a switch-shaped image behindthe switch (this implementation assumes that the switch is positioned by autolayout):

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),
    ])
}

[But see now my other answer.]

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