Best way to communicate between UITableViewCell and UIViewController

The code below works, but probably the best way. My goal is to call the UIViewController function from the UITableCell when exiting edit mode.

I do this by setting an instance of the UIViewController link to each UITableViewCell, and then I call the CancelDelete () function to change the state of the UITableViewCell.

The code seems inefficient because for each MyCell I first create an instance of MyViewContoller as a public variable, and then replace it with a link to the UIViewController when I initialize the UITableView.

Is there a better way to do this?

class MyCell : UITableViewCell
{
    var previousState : UITableViewCellStateMask = UITableViewCellStateMask.allZeros

    // This holds a reference to the parent view controller
    // Seems wasteful to instantiate since it gets replaced
    var controller:MyViewController = MyViewController()

    // This is called when the user aborts edit mode
    override func willTransitionToState(state: UITableViewCellStateMask) {

        if state & UITableViewCellStateMask.ShowingEditControlMask != nil {
            if previousState & UITableViewCellStateMask.ShowingDeleteConfirmationMask != nil { 

            // send notification to controller 
            controller.CancelDelete(self)
        }
    }

    previousState = state
    }    
}


class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        // Give cell access to this controller                        
        var cell:MyCell = tableView.dequeueReusableCellWithIdentifier("cell") as MyCell
        cell.controller = self
        cell.tag = indexPath.row
    }

    // This is called from the table cell
    func CancelDelete(cell:MyCell) {
            editButtons[cell.tag].hidden = false
    }

}
+4
source share
1 answer

controller MyViewController! MyViewController. , nil.

controller :

var controller: MyViewController! = nil

, (!), : https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html ( ).

+2

All Articles