UITableViewCell 和 UIViewController 之间最佳的通信方式

5
下面的代码可行,但可能存在更好的方法。我的目标是在退出编辑模式时从UITableCell调用一个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
    }

}
1个回答

3

1
那个有效。是的,我显然仍需要基础的Swift培训。这是一种正确的通信技术吗?我希望能够在不必明确设置的情况下确定UITableViewCell的拥有ViewController。 - billd
我不知道是否有正确的方法,但这种方法可以在不需要占位符的情况下工作。 - sameer-s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接