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

标签 uitableview swift uiviewcontroller

下面的代码有效,但可能有更好的方法。我的目标是在退出编辑模式时从 UITableCell 调用 UIViewController 函数。

我通过为每个 UITableViewCell 设置实例化的 UIViewController 引用,然后在 UITableViewCell 状态更改时调用函数 CancelDelete() 来实现这一点。

代码似乎效率低下,因为对于每个 MyCell,我首先将占位符 MyViewContoller 实例化为公共(public)变量,然后在 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
    }

}

最佳答案

controller 的类型更改为 MyViewController! 而不是 MyViewController。此外,将其设置为默认值 nil

controller 的声明应该是这样的:

var controller: MyViewController! = nil

如果您对以感叹号 (!) 结尾的类型有任何疑问,请查看: https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html (在名为Optionals 的部分)。

关于uitableview - UITableViewCell 和 UIViewController 之间通信的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129559/

相关文章:

ios - 在 View Controller 之间传递数据

objective-c - UISlider 在最大边缘位置不响应

ios - UITableView:如何将页脚附加到具有分组动态原型(prototype)单元格的部分?

iOS:使用另一个类中定义的 UITableViewCell 中按钮的选定状态填充数组

ios - 从核心数据添加新实体后重新加载 UITableView

swift - 将结果 Firestore 到字典或数组中(Swift)?

ios - MultipeerConnectivity 在 iOS 14 上无法按预期工作

ios - UITableView 搜索后复选标记位于错误的位置

ios - 如何限制 AVAssetWriter 在编码视频时使用过多内存?

ios - 在 iOS5.1/6 中,presentViewController 和 viewDidAppear 没有被调用