我正在嘗試創建一個包含 100 個按鈕 (10x10) 的網格
下面的代碼創建了它們,但是我怎樣才能給它們一個 ID,以便我可以識別每一個,甚至在我單擊一個或更改其顏色等時隱藏它們?
func createButtonGrid(colourArray: Array<String>) {
let spacing = 35
var xPos = 25
var yPos = 150
for i in 0...99 {
print(String(i))
createButton(xPos:xPos, yPos: yPos, colour: colourArray[i] , title: String(i))
xPos = xPos spacing
if i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i == 59 || i == 69 || i == 79 || i == 89 {
xPos = 25
yPos = yPos spacing
}
}
}
func createButton(xPos: Int, yPos:Int, colour: String, title: String) {
let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
gridButton.configuration = plainButtonConfig(colour: colour)
view.addSubview(gridButton)
}
uj5u.com熱心網友回復:
以下函式將創建按鈕,將它們顯示在 10x10 網格中,并給它們一個標簽:
func initializeButtons() {
let spacing = 35
var xPos = 25
var yPos = 150
for i in 0...99 {
let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
gridButton.backgroundColor = UIColor.systemPink
gridButton.layer.cornerRadius = 5
gridButton.tag = i
gridButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
view.addSubview(gridButton)
xPos = xPos spacing
if i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i == 59 || i == 69 || i == 79 || i == 89 {
xPos = 25
yPos = yPos spacing
}
newButtons.append(gridButton)
}
}
然后我們可以創建一個函式,當你點擊按鈕時會有一個動作。
@objc func buttonAction(sender: UIButton!) {
print(sender.tag)
}
uj5u.com熱心網友回復:
重構您的 createButton() 方法以將按鈕作為函式結果回傳。將按鈕保存到陣列中。您已經在使用 for 回圈。陣列中按鈕的索引將是i每次通過回圈的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515821.html
標籤:迅速按钮
