user616076 user616076 - 1 month ago 20
iOS Question

How to add event to my CustomCell in Swift3

I have a UITableView which has rows which include two UISwitch buttons. Until I upgraded to Xcode8 it worked with me adding a protocol to the view controller like this

protocol CustomCellDelegator {
func callSegueFromCell()
}


Then I added the following to my CustomCell swift file which handles the outlets for my custom cell.

open class CustomTableViewCell: UITableViewCell {
var delegate:CustomCellDelegator!

@IBOutlet weak var uidLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var operatedSwitch: UISwitch!
@IBOutlet weak var switchRTN: UISwitch!

override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

@IBAction func operatedSwitchChange() {
if operatedSwitch.isOn {
AppDelegate.myGlobalVars.gSwitchType = "OpsOn"
}
else {
AppDelegate.myGlobalVars.gSwitchType = "OpsOff"
}
if(self.delegate != nil){ //Just to be safe.
self.delegate.callSegueFromCell()
}
}

@IBAction func rtnSwitchChange() {
if switchRTN.isOn {
AppDelegate.myGlobalVars.gSwitchType = "RtnOn"
}
else {
AppDelegate.myGlobalVars.gSwitchType = "RtnOff"
}
if(self.delegate != nil){ //Just to be safe.
self.delegate.callSegueFromCell()
}
}
}


Until I upgraded this worked and delegate always had a value, now it is always nil and the segue is never called.

What do i need to do differently since I upgraded to get this working again?

Answer

Make sure you've assigned your delegate in the ViewController:

// Make your ViewController conform to the protocol
class MyViewController: CustomCellDelegator {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath) as! CustomTableViewCell            
        cell.delegate = self

        return cell
    }

    func callSegueFromCell() {
      // perform your segue here
    }
}
Comments