I'm working on a shopping app project where customers can browse through products and add them to their cart, but am having trouble figuring out how to handle button presses within the tableViewCell. They way I want it to work is that when the empty circle button is pressed, the image changes to a filled circle with a checkmark, and the product within that cell is added to the customers "cart". The "cart" consists of two arrays products
and quantities
held within my CustomerOrder object.
Here's what the tableView looks like:
Here's my code so far:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductToBuyCell") as! ProductToBuyCell
//Configure the Selection Button
cell.selectButton.tag = indexPath.row
cell.selectButton.addTarget(self, action: #selector(ItemSelected), for: .touchUpInside)
let product = productsArray[indexPath.row]
//configure cell
cell.productImg.image = product.productPhoto
cell.productImg.contentMode = .scaleAspectFit
cell.productName.text = product.Name
cell.price.text = "$\(product.price)"
return cell
}
// func for when the selectButton is tapped
// tag is equal to indexPath.row
@objc func ItemSelected(sender: UIButton) {
sender.imageView?.image = UIImage(systemName: "checkmark.circle.fill")
let product = productsArray[sender.tag]
newOrder.products.append(product)
newOrder.quantities.append(1)
}
So if someone could please explain how to properly handle events that are caused by elements within a UITableViewCell and how to get the buttons image to change, that would be very much appreciated.