我在 View Controller 中创建了一个 TableView ,并试图设置它将拥有的行数。该金额从数据库返回,然后传递给正确的方法(见下文)。问题是可见的行数与从数据库返回的行数不同。
在 .viewDidLoad() 中
self.activeIDs.delegate = self
self.activeIDs.dataSource = self
self.activeIDs.rowHeight = 30
self.activeIDs.reloadData()
应该“设置” TableView 的方法
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = activeIDs.dequeueReusableCellWithIdentifier("idCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = "Test"
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
var numberOfRows = 0 //Assigning default value
SQLHandler.getActiveIDAmount {
amountOfIDs in
numberOfRows = amountOfIDs.description.toInt()!
println(numberOfRows) //Displays correct (database) value
}
return numberOfRows //Returns correct value EDIT: wrong value.
}
我总是没有获得所需的行数 (4),尽管我从数据库中获得了值,但最终得到的是 6? TableView 的屏幕截图:http://gyazo.com/753f326177dc8cd6b1734f4d19681d71
问题是什么?我做错了什么?
最佳答案
您调用 SQLHandler 的方法是一个完成处理程序,这意味着 swift 将继续执行您的代码,并且在(并返回 numberOfRowns = 0)之后(当请求完成时)它将返回到 block :
SQLHandler.getActiveIDAmount {
amountOfIDs in
numberOfRows = amountOfIDs.description.toInt()!
println(numberOfRows) //Displays correct (database) value
//add the values returned to your dataset here
//call refresh table and dispatch in the main thread in case
//this block is running in a background thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
并打印行数。
你需要做的是调用函数SQLHandler.getActiveIDAmount
代码中的其他地方和 call table.reloadData()
回调结束后。
希望对你有帮助!
关于ios - UITableView 未显示正确的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30768524/