[英]Swift 2 - for loop create multiple UIButtons
我有一個for循環,該循環創建多個按鈕,具體取決於如何注冊用戶。
按鈕創建良好,我向按鈕添加了一個目標,該目標需要打印已按下哪個按鈕以傳遞值。
到目前為止,我有:
func loadUserVideos() {
let userVideoNames = ["andrew", "john", "verya", "patry", "gabriy"]
let countUserNames = userVideoNames.count - 1
for index in 0...countUserNames {
//print("\(index) times 5 is \(index * 5)")
//UIBUTTON PLAY VIDEO USER
let customButtonPlayVideoUser = UIButton(frame: CGRectMake(145, 32, 64, 64))
let imageCustomUserBtn = UIImage(named: "video-play.png") as UIImage?
customButtonPlayVideoUser.setImage(imageCustomUserBtn, forState: .Normal)
customButtonPlayVideoUser.addTarget(self, action: "CustomUserVideobtnTouched:", forControlEvents:.TouchUpInside)
customViewUser.addSubview(customButtonPlayVideoUser)
}
}
func CustomUserVideobtnTouched(sender: UIButton, index: Int){
print(index)
}
如何將值傳遞給動作函數,以便應用程序可以查看已按下哪個按鈕?
您可以使用標簽值:
for index in 0...countUserNames {
//print("\(index) times 5 is \(index * 5)")
//UIBUTTON PLAY VIDEO USER
let customButtonPlayVideoUser = UIButton(frame: CGRectMake(145, 32, 64, 64))
let imageCustomUserBtn = UIImage(named: "video-play.png") as UIImage?
customButtonPlayVideoUser.setImage(imageCustomUserBtn, forState: .Normal)
customButtonPlayVideoUser.addTarget(self, action: "CustomUserVideobtnTouched:", forControlEvents:.TouchUpInside)
customViewUser.addSubview(customButtonPlayVideoUser)
/// set tag
customButtonPlayVideoUser.tag = index
}
接着
func CustomUserVideobtnTouched(sender: UIButton){
print(sender.tag)
}
您可以將索引設置為按鈕標簽屬性,並在選擇器方法中獲取類似的索引,
sender.tag
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.