简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM