1

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

1 Answer 1

1

A better approach here is to subclass UIButton so button will hold a product as follow:

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

}

Then instead of UIButton you will need to create a ProductButton and get the product in button's action function

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.