在struct中创建UIButton

时间:2017-06-14 14:15:49

标签: swift

情况

嗨!我的产品有以下结构(struct Product),以及为每个产品添加UIButton的以下函数(func createButton(...)

//struct.swift
struct Product {
  var name: String
  var price: Double
  var xPos: Double
  var yPos: Double
  var buttonWidth: Double
  var buttonHeight: Double
}

//ViewController.swift, 
func createButton(product: Product, gridWidth: Double,gridHeight: Double ) {
    let xPos: Double = product.xPos * gridWidth
    let yPos: Double = product.yPos * gridHeight
    let buttonWidth: Double = product.buttonWidth * gridWidth
    let buttonHeight: Double = product.buttonHeight * gridHeight

    let button = UIButton(frame: CGRect(x: xPos, y: yPos, width: buttonWidth, height: buttonHeight))
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

    viewProducts.addSubview(button)
}

for product in products {
  createButton(product: product, gridWidth: gridWidth, gridHeight: gridHeight)
}

问题

现在,当我点击某个按钮时,我需要检索产品实例,以便将其添加到order。我应该做那样的事情,我的按钮会用产品创建吗?我试过但没有成功。

struct Product {
  //[ same a before here ]
  button: UIButton
}

PS:对Swift来说很新; - )

1 个答案:

答案 0 :(得分:1)

这里更好的方法是将UIButton子类化,因此按钮将保存产品,如下所示:

class ProductButton : UIButton{

    let product : Product

    init(frame: CGRect, product : Product) {
        self.product = product
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

然后,您需要创建一个UIButton而不是ProductButton,并在按钮的动作功能中获取产品

func createButton(product: Product, gridWidth: Double,gridHeight: Double ) {
    let xPos: Double = product.xPos * gridWidth
    let yPos: Double = product.yPos * gridHeight
    let buttonWidth: Double = product.buttonWidth * gridWidth
    let buttonHeight: Double = product.buttonHeight * gridHeight

    let button = ProductButton(frame: CGRect(x: xPos, y: yPos, width: buttonWidth, height: buttonHeight), product : product)
    button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)

    viewProducts.addSubview(button)
}

func buttonAction(button : ProductButton){
    // Get product here...
    let product = button.product
}