下面的代码可行,但可能存在更好的方法。我的目标是在退出编辑模式时从UITableCell调用一个UIViewController函数。
我通过将已实例化的UIViewController引用设置到每个UITableViewCell中来完成这个过程,然后在UITableViewCell状态改变时调用CancelDelete()函数。
由于对于每个MyCell,我首先实例化一个占位符MyViewContoller作为公共变量,然后在UITableView初始化时替换它与UIViewController引用,所以代码似乎效率低下。
有没有更好的方法来完成这个任务?
我通过将已实例化的UIViewController引用设置到每个UITableViewCell中来完成这个过程,然后在UITableViewCell状态改变时调用CancelDelete()函数。
由于对于每个MyCell,我首先实例化一个占位符MyViewContoller作为公共变量,然后在UITableView初始化时替换它与UIViewController引用,所以代码似乎效率低下。
有没有更好的方法来完成这个任务?
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
}
}