ios - 如何将数据从 VC 传递到 Cell?

标签 ios swift uiviewcontroller cell

我想知道如何将数据从 ViewController 传递到单元格?

我是初学者,所以我可能会监督显而易见的 :P

我有一个家庭 VC,当您按下 commentButton 时,您将进入包含帖子 postId 的 CommentVC。 因为我希望能够喜欢一条评论(效果很好)并注意到用户他的评论被喜欢(现在不起作用)所以我不仅需要在 commentVC 中拥有 postId(其中包含正确的评论) ) 也在单元格中。

这是我将数据从 HomeVc 传递到 CommentVC 的代码

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "CommentSegue" {
        let commentVC = segue.destination as! CommentViewController
        let commentCell = CommentTableViewCell()
        let postId = sender as! String
        commentCell.postId = postId
        commentVC.postId = postId
    }
}

当我在 CommentVc 和 CommentCell 中打印出两个变量时,只有 CommentVc 显示正确的变量,而 Cell 的打印输出语句为“nil”。

知道如何通过它吗?

最佳答案

您不应该通过调用您的自定义类初始化器来实例化 UITableViewCell,但您应该在您的 UITableViewController 类(或符合 UITableViewContollerDataSource 协议(protocol))。

在使用 创建单元格时,将要在单元格中显示的数据传递给 TableView Controller 和数据源方法(例如 tableView(_:cellForRowAt:)) dequeueReusableCell(withIdentifier:) 将数据分配给特定的单元格。

关于ios - 如何将数据从 VC 传递到 Cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44785132/

相关文章:

从脚本生成构建时,SwiftSupport 文件夹未包含在 IPA 中

ipad - 为什么 [UIViewController presentModalViewController :animated:] transitioning the modal view in from the left?

ios - 记住 UITableView 上的滚动位置

iphone - 为什么我不能将子 Pane plist 文件添加到项目的 Settings.bundle 中?

ios - iOS 7开发人员-最小化应用会导致UIWebView嵌入式YouTube播放器停止播放

ios - 嵌套枚举可以保存在 UserDefaults 中吗?

swift - 更新位置时 MKmapview 会重置

ios - UIViewController init 方法中的隐式解包选项

swift - 将 Swift 泛型类转换为具有类型别名的协议(protocol)

ios - 新的 iOS 13 模态演示 : Presenting Controller Doesn't Move Down