从Internet下载每个单元格之后,如何在UitaiteViewCell中重新加载数据



我有一个带有某些单元格的表视图,每个单元格将从Internet获取数据。我的tableViewCell的功能:

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("placeCell", forIndexPath: indexPath) as! WeatherTableViewCell
                ......
        //Create Url here...
                ......
        let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(url!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
            if error == nil {
                let dataObject = NSData(contentsOfURL: location)
                //                println("dataObject:(dataObject)")
                .........
        // Got data text here
                .........
                println("dataText: (self.dataText)")

            }
            cell.label.text = "(self.dataText)"

        })
        downloadTask.resume()
        return cell
    }

一切正常,我可以为每个单元格获得所有数据,但是单元格的标签不会更新Datatext。当我获得每个单元格的数据时,我希望单元格更新Datatext。我该怎么做?

您必须在主线程中更新UI。
更换此:

cell.label.text = "(self.dataText)"

与此:

dispatch_async(dispatch_get_main_queue()) {
        cell.label.text = "(self.dataText)"
}

请尝试。

var indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.none)

您也可以使用以下代码以及

来达到您的要求
// on main thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // do your background code here
        // schedule data download here
        dispatch_sync(dispatch_get_main_queue(), ^{
            // on main thread
            // assign the text to label here
            // also be sure to assign the text to label of current index path cell
        });
    });

  [1]: http://stackoverflow.com/questions/30343678/how-can-i-reload-data-in-uitableviewcell-after-i-download-data-for-each-cell-fro?answertab=oldest#tab-top

最新更新