按下时更改程序化创建按钮的颜色

时间:2018-03-15 01:18:34

标签: ios swift uibutton

我正在使用一个功能为我的游戏创建多个按钮。

func createButton() {
    let button = UIButton()
    button.setTitle("", for: .normal)
    button.frame = CGRect(x:15, y: 50, width: 200, height:100)
    button.backgroundColor = UIColor.red
    self.view.addSubview(button)
    button.addTarget(self, action: Selector(("buttonPressed:")), for: 
    .touchUpInside)
}

我在viewDidLoad函数中调用此函数一次以进行测试,但我不知道我应该在buttonPressed()函数中添加哪些代码来改变我的按钮的颜色?我试着做了

self.backgroundColor = UIColor.blue

但这不起作用。我也尝试使用UIButton和按钮而不是self,但这两者都不起作用。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您的代码不是Swift 4代码。以下是如何执行此操作:

  • 按照您的方式创建按钮,但将Selector更改为#selector

    func createButton() {
        let button = UIButton()
        button.setTitle("", for: .normal)
        button.frame = CGRect(x:15, y: 50, width: 200, height:100)
        button.backgroundColor = UIColor.red
        self.view.addSubview(button)
        button.addTarget(self, action: #selector((buttonPressed)), for: .touchUpInside)
    }
    
  • 使用自动添加的sender

    @objc func buttonPressed(sender: UIButton) {
        sender.backgroundColor = UIColor.blue
    }
    

另外我可以提供一些建议吗?

  • 在更改之前检查背景颜色。毫无疑问,不必更换已经是蓝色的按钮。
  • 由于您没有为按钮设置标题,请设置tag属性(您甚至可以将其作为参数添加到createButton)。通过这种方式,您可以知道点击了哪个按钮。

答案 1 :(得分:0)

只需将按钮设为实例属性即可。

let changingButton = UIButton()

func createButton() {
    changingButton.backgroundColor = UIColor.red
    changingButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}

@objc func buttonPressed() {
    changingButton.backgroundColor = UIColor.blue
}