Search code examples
iosuitableviewswift3addtarget

Swift 3 - button in .xib custom tableviewcell is not performing action


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?


Solution

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