Situation
Hi! I have the following structure (struct Product) for my products and the following function to add a UIButton for each product (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)
}
Question
Now, when I click on a button, I need to retrieve the product instance so I can add it to an order. Should I do something like that, and my button will be created with the product? I tried but without success.
struct Product {
//[ same a before here ]
button: UIButton
}
PS: very new to Swift ;-)