Ios 从internet下载每个单元格的数据后,如何在UItableviewCell中重新加载数据?
我有一个带有一些单元格的tableview,每个单元格将从internet获取数据。 我的tableviewcell函数如下所示:Ios 从internet下载每个单元格的数据后,如何在UItableviewCell中重新加载数据?,ios,uitableview,swift,nsurlsession,Ios,Uitableview,Swift,Nsurlsession,我有一个带有一些单元格的tableview,每个单元格将从internet获取数据。 我的tableviewcell函数如下所示: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("
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
}
一切正常,我可以得到每个单元格的所有数据,但单元格的标签不会更新数据文本。
当我获得每个单元格的数据时,我希望单元格更新数据文本。我该怎么做?您必须在主线程中更新UI。
替换此项:
cell.label.text = "\(self.dataText)"
为此:
dispatch_async(dispatch_get_main_queue()) {
cell.label.text = "\(self.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)
请试试这个
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
您也可以使用下面的代码来实现您的需求
// 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
你应该更新主线程上的标签你应该更新主线程上的标签太棒了!快乐编码!伟大的快乐编码!