如何从另一个 ViewController 修改 UITableView 的单元格 [英] How to modify a cell of UITableView from another ViewController

查看:23
本文介绍了如何从另一个 ViewController 修改 UITableView 的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VC#1 中,我有一个 UITableView.当我点击一个单元格时,我会被带到 VC#2,其中显示了有关该单元格的信息.

In VC#1, I have a UITableView. When I tap on a cell, I am brought to VC#2 where information about that cell is displayed.

我希望能够在 VC#2 中按下一个按钮来改变它在 VC#1 中对应的单元格的标题,但我不知道如何做到这一点?

I want to be able to press a button in VC#2 which changes the title of the cell it corresponds with in VC#1, but I am confused on how to do this?

我是否应该在 VC#2 中创建一个变量来保存被点击的单元格的 indexPath,然后从 VC#2 调用 VC#1 中的一个函数,该函数使用该 indexPath 来更新单元格?如果我这样做了,VC#1 不需要是静态的,所以我知道我正在修改 VC#1 的正确实例吗?我正在使用 push segue 和导航控制器返回,因此创建 VC#1 的新实例不会像我相信的那样引用我试图修改的同一个 VC?

Should I create a variable in VC#2 to save the indexPath for the cell that was tapped, and then call a function in VC#1 from VC#2 that uses that indexPath to update the cell? If I did this, wouldn't VC#1 need to be static so I know I'm modifying the right instance of VC#1? I'm using a push segue and a navigation controller to go back, so creating a new instance of VC#1 wouldn't reference the same VC im trying to modify as I believe?

有没有更简单的方法来做到这一点?

Is there an easier way to do this?

推荐答案

你应该使用委托模式.

VC1 应该知道 VC2 显示的是哪个单元格.您应该在 VC1 中有一个 IndexPath 属性,用于存储 VC2 当前显示的单元格,对吗?

VC1 should know what cell that VC2 is showing. You should have an IndexPath property in VC1 that stores what cell is VC2 currently displaying, right?

现在,创建一个名为 VC2Delegate 的协议:

Now, create a protocol called VC2Delegate:

protocol VC2Delegate : class {
    func titleDidChange(_ vc2: VC2, to title: String)
}

现在,在 VC2 中添加此属性:

Now, add this property in VC2:

weak var delegate: VC2Delegate?

现在,当你认为单元格的标题应该改变时,调用委托:

Now, when you think the title of the cell should change, call the delegate:

delegate?.titleDidChange(self, to: "Some Title")

这就是 VC2 的全部内容.

That's all for VC2.

使VC1符合VC2Delegate:

extension VC1: VC2Delegate {
    func titleDidChange(_ vc2: VC2, to title: String) {
        // set the text of the table cell here...
    }
}

现在,当您从 VC1 向 VC2 传递数据时,可能在 prepareForSegue 方法中,执行

Now, when you are passing data to VC2 from VC1, probably in the prepareForSegue method, do

vc2.delegate = self

此处了解有关代表的更多信息.

这篇关于如何从另一个 ViewController 修改 UITableView 的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆