UISwitch设置打开/关闭图像

时间:2016-04-29 03:03:21

标签: xcode swift uiswitch

我想像我这样设置我的开关:

enter image description here

但我尝试使用ios9,它不起作用。 我在苹果UISwitch Class Reference中看到过。 它说:

讨论 在iOS 7中,此属性无效。

iOS 9怎么样?任何一次成功?

我的代码:

switch1 = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
switch1.on = true
switch1.onTintColor = UIColor.lightGrayColor()
switch1.tintColor = UIColor.greenColor()
switch1.thumbTintColor = UIColor.blackColor()

//设置开/关图像

switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")

3 个答案:

答案 0 :(得分:17)

改为使用UIButton

let switchButton = UIButton(type: .Custom)
switchButton.selected = true
switchButton.setImage(UIImage(named: "on-switch"), forState: .Selected)
switchButton.setImage(UIImage(named: "off-switch"), forState: .Normal)

使用switchButton.selected代替switch1.on。点击switchButton.selected时,您必须切换switchButton.selected = !switchButton.selected

答案 1 :(得分:1)

对于 iOS 1 3,您可以这样操作:

   let switcher = UISwitch()
    switcher.addTarget(self, action: #selector(pressed), for: .valueChanged)
    

 @objc func pressed(sender: UISwitch) {
        let color = UIColor(patternImage: UIImage(named: sender.isOn ? "on.png": "off.png")!)
        if sender.isOn {
            sender.onTintColor = color
        } else {
            sender.tintColor = color
            sender.subviews[0].subviews[0].backgroundColor = color
        }
    }

注意:您的图片应如下所示:

enter image description here

然后最终结果是:

enter image description here

答案 2 :(得分:0)

不是您问题的确切答案,但是,如果您希望以编程方式(可以向其中添加文本)使用完全自定义的按钮开关,这也将起作用:

 import UIKit

 class RDHiddenVisibleButton: UIButton {

    // Hidden / Visible Button Function
    var isOn = false

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

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

    func initButton() {
        layer.borderWidth = 2.0
        layer.borderColor = Colors.radiusGreen.cgColor
        layer.cornerRadius = frame.size.height/2

        setTitleColor(Colors.radiusGreen, for: .normal)
        addTarget(self, action: #selector(RDHiddenVisibleButton.buttonPressed), for: .touchUpInside)

    }

@objc func buttonPressed() {
        activateButton(bool: !isOn)
    }

    func activateButton(bool: Bool) {

        isOn = bool

        let color = bool ? Colors.radiusGreen : .clear
        let title = bool ? "Hidden" : "Visible"
        let titleColor = bool ? . white : Colors.radiusGreen

        setTitle(title, for: .normal)
        setTitleColor(titleColor, for: .normal)
        backgroundColor = color
    }
}