簡體   English   中英

如何在運行時創建未知數量的動態按鈕? 如何在運行時為每個按鈕的每個按鈕添加動作偵聽器?

[英]How to create dynamic unknown number of buttons on runtime ? How to add each of them a action listener to all buttons on runtime?

我想要這樣的構建界面。 用戶將輸入要顯示的按鈕范圍。 我是iOS開發的新手。 我不知道如何在運行時plz幫助下完成所有操作。我想在數據庫中存儲按下和未按下的按鈕的數量,如何實現此目的的任何解決方案。

先感謝您

addTarget是android中類似動作監聽器的按鈕的函數。

dynamicButtonInstance.addTarget(self,action:#selector(handleRegister),用於:.touchUpInside)

handleRegister是類中的函數。

創建按鈕是

let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 50 , g: 80, b: 130)
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action:#selector(handleRegister), 
for:.touchUpInside)
Hi you can achieve this by using collectionView(is the efficient approach) or by adding the buttons
So while adding button just add a tag of button with +1 and when user click the button just fetch button tag and you will get which button is clicked.
Please find below sample

var prevBtn = 0

func addButton()

let button = UIButton()
button.tag = prevBtn.tag + 1
button.addTarget(self, action:#selector(handleButtonAction), 
for:.touchUpInside)
prevBtn = button.tag
}

func handleButtonAction(button: UIButton){

print(button.tag)

}

Thanks

暫無
暫無

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

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