简体   繁体   English

如何以编程方式将自定义单元格插入TableView

[英]How do I Insert Custom Cell into TableView Programmatically

I am trying to insert my custom cells into my table view with data that is loaded from a web request, but the table insert script is running before the data is loaded which has me ending up with a blank table. 我试图将自定义单元格与从Web请求中加载的数据一起插入到我的表视图中,但是表插入脚本在加载数据之前运行,这使我最终得到一个空白表。

Currently my code is this and I have tested it to work with dummy data: 目前,我的代码是这样,我已经对其进行了测试,可以与虚拟数据一起使用:

    public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        mainTableView.estimatedRowHeight = 50.0
        mainTableView.rowHeight = UITableViewAutomaticDimension
        var cell : postWithTitleAndImageTableViewCell = mainTableView.dequeueReusableCellWithIdentifier("postWithTitleAndImage") as postWithTitleAndImageTableViewCell
        let image = UIImage(named: "chainz on deck.jpg")
        var id = json[indexPath.row]["id"] as String
        var title = json[indexPath.row]["name"] as String
        var text = json[indexPath.row]["post"] as String
        var time = json[indexPath.row]["time"] as String
        var popularity = json[indexPath.row]["popularity"] as String
        //add clientid
        cell.setCell(id, title: title, image: image!, text: text, time: time, popularity: popularity)
        return cell as postWithTitleAndImageTableViewCell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)! Which the ID is: \(readIDs[indexPath.row])")
    }

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

The code does exactly what it's supposed to, except the json variable is loaded from a web request and the table is trying to insert before the data is actually loaded. 该代码完全按照预期的方式运行,只是从Web请求中加载了json变量,并且该表正试图在实际加载数据之前插入。 How should I fix this? 我该如何解决? Is there a way to call for a manual insertion of a custom cell, or is there a way to call the tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) function once the data is loaded? 一旦加载数据tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)是否有办法调用手动插入自定义单元格,还是有办法调用tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)函数? What should I do? 我该怎么办?

Using mainTable.reloadData() worked. 使用mainTable.reloadData()起作用。 Thanks @Paulw11 谢谢@ Paulw11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM