The code below works but there is probably a better way. My goal is to call a UIViewController function from the UITableCell when aborting from edit mode.
I am doing this by setting an instantiated UIViewController reference to every UITableViewCell and then calling a function, CancelDelete(), on the UITableViewCell state change.
The code seems inefficient since for every MyCell I first instantiate a placeholder MyViewContoller as the public variable and then replace it with reference to the UIViewController when the UITableView initializes.
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
}
}
Change the type of controller
to MyViewController!
instead of MyViewController
. Also, set it to a default value of nil
.
The declaration of controller
should look like this:
var controller: MyViewController! = nil
If you have any questions about types that end with an exclamation mark (!
), look at:
https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
(in the section named Optionals).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With