1
如何爲我的集合中的每個可用項目添加按鈕,而無需爲每個項目編寫一次代碼?爲集合中的每個項目添加按鈕
這是我到目前爲止有:
func drawInventory() {
if Person.inventory.itemsInBag[0].Id > 0 {
let itemButton1 = UIButton()
itemButton1.setImage(Person.inventory.itemsInBag[0].Image, for: .normal)
itemButton1.frame = CGRect(x: 300, y: 185, width: 30, height: 30)
itemButton1.addTarget(self, action: #selector(tapItemInInventory), for: .touchUpInside)
view.addSubview(itemButton1)
}
if Person.inventory.itemsInBag[1].Id > 0 {
let itemButton1 = UIButton()
itemButton1.setImage(Person.inventory.itemsInBag[1].Image, for: .normal)
itemButton1.frame = CGRect(x: 300+40, y: 185, width: 30, height: 30)
itemButton1.addTarget(self, action: #selector(tapItemInInventory2), for: .touchUpInside)
view.addSubview(itemButton1)
}
}
func tapItemInInventory() {
print(self.Person.inventory.itemsInBag[0].Name + "Pressed")
}
func tapItemInInventory2() {
print(self.Person.inventory.itemsInBag[1].Name + "Pressed")
}
是'map'必需的嗎?無法直接在集合上調用'enumerated'? – Losiowaty
良好的通話。這只是我忘記刪除關鍵字...謝謝! – tomahh
@Тимур-Хасанов我更新了我的答案,我用obective-c風格編寫了選擇器。 – tomahh