加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:57:30 所属栏目:百科 来源:网络整理
导读:下面的代码有效,但可能有更好的方法.我的目标是在从编辑模式中止时从UITableCell调用UIViewController函数. 我这样做是通过为每个UITableViewCell设置一个实例化的UIViewController引用,然后在UITableViewCell状态更改时调用一个函数CancelDelete(). 代码似
下面的代码有效,但可能有更好的方法.我的目标是在从编辑模式中止时从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
    }

}

解决方法

将控制器的类型更改为MyViewController!而不是MyViewController.另外,将其设置为默认值nil.

控制器的声明应如下所示:

var controller: MyViewController! = nil

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读