代码之家  ›  专栏  ›  技术社区  ›  Andrew Tuzson

无法在表视图单元格中显示来自应用程序委托的数组数据

  •  0
  • Andrew Tuzson  · 技术社区  · 8 年前

    我已经构建了一个meme生成器,并在选项卡栏视图控制器中嵌入了处理meme创建的视图控制器。第一个选项卡显示一个表视图,我正在尝试让该表视图在通过活动视图保存Meme后显示Meme。我已经在我的应用程序代理文件中添加了一个meme数组(我知道这有争议,但这是本练习的要求),我已经确认meme正在保存并传递到应用程序代理文件。

    每当用户创建新的meme时,我想在表视图中显示保存的meme的图像和文本。这是我所拥有的,但这不起作用。

    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 是指向回购的链接。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Mo Abdul-Hameed Martheli    8 年前

    当您在 UITabBar 选项卡, viewDidLoad 不会触发,仅在创建选项卡栏后才会触发。

    为了使表视图反映更改,您需要在 viewWillAppear 歪投球 viewDidLoad视图 .

    因此,您将拥有:

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

    您需要向 memes 这样地:

    var memes: [Meme]! {
        didSet {
            tableView.reloadData()
        }
    }
    

    编辑:@AndreaMugnani提到,您需要连接 IBOutlet 对于您的表视图:

    @IBOutlet weak var tableView:UITableView!