【问题标题】:Best way to communicate between UITableViewCell and UIViewControllerUITableViewCell 和 UIViewController 之间通信的最佳方式
【发布时间】:2015-01-24 19:51:16
【问题描述】:

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

我这样做是通过为每个 UITableViewCell 设置一个实例化的 UIViewController 引用,然后在 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
    }

}

【问题讨论】:

    标签: uitableview swift uiviewcontroller


    【解决方案1】:

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

    controller 的声明应如下所示:

    var controller: MyViewController! = nil
    

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

    【讨论】:

    • 那行得通。是的,我显然还需要补习 Swift 培训。这是一种正确的沟通技巧?我曾希望无需显式设置即可确定 UITableViewCell 的所属 ViewController。
    • 我不知道是否有正确的方法,但这不需要占位符。
    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2015-08-10
    相关资源
    最近更新 更多