2017-02-27 11 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()が2回呼び出されます。初めて、商品のインデックスをitemsInBag配列に取得します。 2回目は、Idが0より小さい場合、アイテムを破棄する可能性があるため、アイテムの位置を画面に表示します。

+0

'map'は必要ですか? 'enumerated'をコレクションで直接呼び出すことはできませんか? – Losiowaty

+1

よろしくお願いします。それは私がキーワードを削除することを忘れていた...ありがとう! – tomahh

+0

@Тимур-Хасанов私は自分の答えを更新しました。私はセレクタを完全な形式で書いています。 – tomahh

関連する問題