簡體   English   中英

按下時更改以編程方式創建的按鈕的顏色

[英]Change Color of Programmatically Created Button when Pressed

我正在使用一個函數為我的游戲創建多個按鈕。

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和button而不是self,但是兩者都不起作用。 我該怎么辦?

您的代碼不是干凈的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的參數)。 這樣,您可以知道點擊了哪個按鈕。

只需將按鈕設為實例屬性即可。

let changingButton = UIButton()

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM