Swift 为集合中的每个项目添加按钮

Swift 为集合中的每个项目添加按钮,swift,class,func,Swift,Class,Func,如何为集合中的每个可用项添加按钮,而不为每个项编写一次代码 这就是我到目前为止所做的: func drawInventory() { if Person.inventory.itemsInBag[0].Id > 0 { let itemButton1 = UIButton() itemButton1.setImage(Person.inventory.itemsInBag[0].Image, for: .normal) itemBu

如何为集合中的每个可用项添加按钮,而不为每个项编写一次代码

这就是我到目前为止所做的:

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")

}
这里,
itemButton
标记
属性用于标识它所属的项。这是传递信息的快速而肮脏的方式,但对于这个简单的例子来说效果很好

更好的解决方案是子类
UIButton
,将其添加为一个属性以引用与其相关的项


另外,
enumerated()
被调用两次。第一次,我们在
itemsInBag
数组中获取项目的索引。第二次,我们在屏幕上获得项目位置,因为如果项目Id小于0,我们可能会丢弃一些项目。

是否需要
映射
?不能对集合直接调用枚举的
吗?很好。只是我忘了删除关键字。。。谢谢@在更新我的答案后,我用OBACTIVE-c风格编写了选择器。
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")
}