我的应用程序需要在加载tableview之前从服务器获取数据。完成获取数据后,如何使用dispatch_async使应用程序更新单元格视图。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = myTable.dequeueReusableCellWithIdentifier("editCell") as! EditTableViewCell
cell.answerText.text = dictPicker[indexPath.row]![dictAnswer[indexPath.row]!]
cell.questionView.text = listQuestion1[indexPath.row]
cell.pickerDataSource = dictPicker[indexPath.row]!
dictAnswer[indexPath.row] = cell.pickerValue
cell.answerText.addTarget(self, action: #selector(AddFollowUpViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingDidEnd)
cell.answerText.tag = indexPath.row
cell.identifier = true
return cell
}
当我习惯上面的代码时,它给我一个错误:dictAnswer为nil。从服务器获取了dictAnswer。我认为原因是在dictAnswer获取之前更新了单元格。但我不知道如何使用dispatch_async。我希望有一些可以给我提示。谢谢
您的UITableViewDataSource函数应引用数组中的行数,如下所示
var data:[String]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
因此,在您的异步函数中,您可以获取数据:
func loadData() {
// some code to get remote data
self.data = result
dispatch_async(dispatch_get_main_queue()) {
tableView.reloadData()
}
}
当您的数组为空时,(data.count返回0)tableView将不会尝试加载任何行并崩溃
Swift 3+更新:
DispatchQueue.main.async {
tableView.reloadData()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句