[英]How to create dynamic unknown number of buttons on runtime ? How to add each of them a action listener to all buttons on runtime?
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.