在Swift中的任何印刷机上更改自定义UIButton的BG颜色

时间:2016-08-05 05:39:50

标签: ios iphone swift uibutton

我有一个自定义的UIButton(SelectionButton),我想知道如何才能使它在推动后背景颜色发生变化 - 导致它为已按下的每个SelectionButton实例保留该颜色。

我可以在一行代码中执行此操作,该代码行适用于每个SelectionButton而无需在IBAction中一次编写一个吗?

4 个答案:

答案 0 :(得分:1)

我建议您使用以下解决方案。对UIButton类进行扩展:

extension UIButton {
override public var selected: Bool {
    didSet {
        if self.selected {
            self.backgroundColor = UIColor.greenColor()
            }
            else {
                self.backgroundColor = UIColor.redColor()
            }
    }
}

}

并且与连接到UIButton的TouchUpInside(或其他事件)的代码相比,只是放了:

@IBAction func myButtonClick(sender: UIButton) {
    sender.selected = !sender.selected
}

答案 1 :(得分:1)

以下是可以更好地满足您需求的解决方案。

这是类选择按钮:

class SelectionButton: UIButton {
override var selected: Bool {
    didSet {
        if self.selected {
            self.backgroundColor = UIColor.greenColor()
        }
        else {
            self.backgroundColor = UIColor.redColor()
        }
    }
}

}

以及将以编程方式创建按钮实例的代码:

    @IBAction func createSelButton(sender: AnyObject) {
    let myButton = SelectionButton()
    myButton.frame = CGRect(x: 100, y: 200, width: 200, height: 25)

    self.view.addSubview(myButton)
    myButton.setTitle("My Selection Button", forState: UIControlState.Normal);
    myButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)

    myButton.addTarget(self, action: "clickButton:", forControlEvents: UIControlEvents.TouchUpInside)
}

最后由selector指向clickButton函数:

    func clickButton(sender: SelectionButton) {
    sender.selected = !sender.selected
}

请记住,在最新版本的Swift中,slector语法已经改变了。

答案 2 :(得分:0)

我认为这会对你有帮助 -

let discoverButton:UIButton = UIButton(frame: CGRect(x:100 , y: 40.0, width: 360.0, height: 70.0 ))
        discoverButton.setBackgroundImage(UIImage(named: "discover-white.png"), forState: UIControlState.Normal)
        discoverButton.setBackgroundImage(UIImage(named: "discover-blue.png"), forState: UIControlState.Focused)
         discoverButton.setBackgroundImage(UIImage(named: "discover-blue.png"), forState: UIControlState.Selected)
        discoverButton.addTarget(APP_DELEGATE, action:#selector(YourClassName.MenuButtonsPrimaryActionTriggered(_:)), forControlEvents: UIControlEvents.PrimaryActionTriggered)
        discoverButton.userInteractionEnabled  = true;
        discoverButton.tag=101



 func MenuButtonsPrimaryActionTriggered(btn:UIButton)->Void
        {
//Action performed on button
        }

答案 3 :(得分:0)

您可以在代码中更改不同状态的颜色,例如

mybutton.setTitleColor(UIColor.redColor(),forState:UIControlState.Selected)