2017-02-27 37 views
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") 

} 

回答

2
func drawInventory() { 
    Person.inventory.itemsInBag.enumerated().filter { $1.Id > 0 }.enumerated().forEach { index, itemAndIndex in 
     let (itemPosition, item) = itemAndIndex 
     let itemButton = UIButton() 

     itemButton.setImage(item.Image, for: .normal) 
     itemButton.frame = CGRect(x: 300 + (40 * itemPosition), y: 185, width: 30, height: 30) 
     itemButton.addTarget(self, action: #selector(tapItemInInventory(_:)), for: .touchUpInside) 
     itemButton.tag = index 
     view.addSubview(itemButton) 
    } 
} 

dynamic func tapItemInInventory(_ button: UIButton) { 
    let item = Person.inventory.itemsInBag[button.tag] 

    print(item.Name + "Pressed") 
} 

這裏,itemButtontag屬性用於識別它屬於哪個項目。它是快速和骯髒的傳遞信息的方式,但適用於這個簡單的例子。

更好的解決方案是子類UIButton,添加一個屬性來引用它所關聯的項目。

另外,enumerated()被調用兩次。第一次,我們得到itemsInBag數組中的項目索引。第二次,我們在屏幕上獲取物品位置,因爲如果它的Id小於0,我們可能會丟棄一些物品。

+0

是'map'必需的嗎?無法直接在集合上調用'enumerated'? – Losiowaty

+1

良好的通話。這只是我忘記刪除關鍵字...謝謝! – tomahh

+0

@Тимур-Хасанов我更新了我的答案,我用obective-c風格編寫了選擇器。 – tomahh

相關問題