无法在表视图单元格中显示App Delegate中的数组数据

问题描述 投票:0回答:1

我已经构建了一个meme生成器,并且我嵌入了视图控制器,用于处理标签栏视图控制器内部的模因创建。第一个选项卡显示一个表视图,我试图通过活动视图保存该表视图后显示模因。我已将memes数组添加到我的App Delegate文件中(我知道这是有争议的,但这是本练习的要求)并且我已确认meme正在保存并传递给app delegate文件。

我想在用户创建新的模因时在表格视图中显示保存的模因图像和文本。这是我拥有的,这是行不通的。

import UIKit

class TableViewMemesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var memes: [Meme]!

    override func viewDidLoad() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        memes = appDelegate.memes
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return memes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        let meme = memes[indexPath.row]
        cell?.imageView?.image = meme.memedImage
        cell?.textLabel?.text = meme.topText
        return cell!
    }

}

我哪里错了? cellForRowAt的过程对我来说仍然是新的和令人沮丧的。 Here是回购的链接。

ios swift tableview
1个回答
3
投票

当您在UITabBar选项卡之间导航时,不会触发viewDidLoad,只有在创建选项卡栏后才会触发它。

为了使表视图反映更改,您需要在viewWillAppear中处理,而不是在viewDidLoad中。

所以你将拥有:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    memes = appDelegate.memes
}

你需要像qzxswpoi这样添加一个属性观察者:

memes

编辑:正如@Andrea Mugnaini所提到的,你需要为你的桌面视图连接一个var memes: [Meme]! { didSet { tableView.reloadData() } }

IBOutlet
© www.soinside.com 2019 - 2024. All rights reserved.