0

I have a tableviewcontroller, where i have created custom tableviewcell in a .xib files.

The button (myButton) is used on myCustomTableViewCell.xib has an outlet to myCustomTableViewCell.swift

I have set an action for the button in the TableViewController.swift file

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = Bundle.main.loadNibNamed("myCustomTableViewCell", owner: self, options: nil)?.first as! myCustomTableViewCell    

cell.myButton.setTitle(arrayOfMyData[indexPath.row].myText, for:.normal )

//other code to set some other cell.attribute values like above (all works)

cell.myButton.actions(forTarget: "myAction", forControlEvent: .touchUpInside)

}

and elsewhere in the TableViewController.swift I have the action:

func myAction(sender: UIButton){
    print("pressed myButton")
}

but myAction is never called / "pressed myButton" is never printed. What am I missing?

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Dave
  • 167
  • 17

1 Answers1

4

You need to use addTarget(_:action:for:) method to add the action for your button not the actions(forTarget:forControlEvent:).

The function actions(forTarget:forControlEvent:) returns the actions that have been added to a control. It doesn't add a target/action.

cell.myButton.addTarget(self,action: #selector(myAction(sender:)), for: .touchUpInside)
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • thank you. i actually had it as addTarget previously but didn't have the syntax right and in looking for a fix found the actions... greatly appreciate the help. – Dave Feb 06 '17 at 16:12
  • @Dave Welcome mate :) – Nirav D Feb 06 '17 at 16:14