0

I have custom file called Menu

import Foundation

class Menu:NSObject{
    var itemName : String?
    var itemURL : String?
    var objectId: String?
    var created: NSDate?
    var updated: NSDate?
}

I am using iCarousel to populate my view and for each cell, I am adding the views manually as with the below code

func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
    var myView : UIView
    let menu = menuItems[index]

    myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 500))
    myView.backgroundColor = UIColor.white.withAlphaComponent(0.7)


    addButton = UIButton(frame: CGRect(x: 150, y: 260, width: 60, height: 20))
    addButton.backgroundColor = UIColor.brown
    addButton.layer.cornerRadius = 0.5 * addButton.bounds.width
    addButton.setTitle("Add", for: .normal)
    addButton.titleLabel?.font = UIFont.systemFont(ofSize: 13)
    addButton.addTarget(self, action:#selector(addItemToCart(menu:)), for: .touchDown)

    myView.addSubview(addButton)

    return myView
}

I have made a class addItemToCart which takes in an input of type Menu, which is to be called whenever the addButton is clicked

func addItemToCart(menu : Menu) -> Void {
    print(menu.itemName)
}

But I am not able to pass the menu type object to it. How can I pass the object to addItemToCart function whenever the button is pressed?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Vidya Sagar
  • 170
  • 1
  • 16

1 Answers1

1

You must set sender in your function:

func addItemToCart(sender : UIButton) -> Void {
    print(menu.itemName)
}

Then set button tag to index in viewForItemAt so you can access on the function

addButton.tag = index

Now you can use your func:

func addItemToCart(sender : UIButton) -> Void {
        let menu = menuItems[sender.tag]
        print(menu.itemName)
}

Source: iOS Swift Button action in table view cell

Lucas Palaian
  • 374
  • 2
  • 12
  • Thank you. That worked perfectly. Although I am curious, is there a way to send datatype (Menu in my case) instead of just index value? – Vidya Sagar Jan 27 '17 at 07:06