swift - 为集合中的每个项目添加一个按钮

标签 swift class func

如何在不为每个项目编写一次代码的情况下为我的收藏中的每个可用项目添加一个按钮?

这是我目前所拥有的:

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

}

最佳答案

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,我们可能会丢弃一些项目。

关于swift - 为集合中的每个项目添加一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42477177/

相关文章:

ios - 没有边框和阴影的 UITextField

ios - DynamicCastClassUnconditional 与自定义单元类

php 类...验证

c# - readonly Func 与方法,性能影响/引擎盖下的东西

ios - Swift:创建一个函数来编辑 UILabel 设置

ios - Storyboard不包含带有标识符的 View Controller ......使用多个 Storyboard文件时

c++ - 类成员函数执行时程序停止工作

c# - 类数组使用产生错误 "NullReferenceException: Object reference not set to an instance of an object"

arrays - 如何按时间顺序遍历数组?

c# - 具有 2 个处理程序的事件 Func<bool> : which return to expect?