我正在用 Swift 编写一个 iOS 应用程序,将来自 API 的数据放入 TableView。目标是用户可以向下滚动连续的博客文章列表。发生的事情是数据很好地填充了第一个屏幕的单元格数量,但是当用户向下滚动时,应用程序崩溃作为单元格属性之一,cellImageView
变为 nil
并展开(因为在单元类的代码中指定了强制展开):
class BlogPostEntryCell: UITableViewCell {
//MARK: Properites
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var bodyTextView: UITextView!
@IBOutlet weak var initialsImageView: UIImageView!
}
这是导致崩溃的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell
apiCaller.getAPIDataThroughAsyncCall(id: nextCell, entry: { cellContent in
DispatchQueue.main.async(execute: {
cell.cellLabel.text = cellContent.labelText
cell.cellTextView.text = cellContent.textViewText
// App crashes at the below line
cell.initialsImageView = self.createPicture(initials: cellContent.pictureText)
})
})
nextCell += 1
return cell
}
有趣的是,如果这样做:
cell.cellLabel?.text = cellContent.labelText
cell.cellTextView?.text = cellContent.textViewText
// App does NOT crash at the below line
cell.initialsImageView? = self.createPicture(initials: cellContent.pictureText)
,应用程序不会崩溃,但数据只会随着用户滚动而一遍又一遍地重复。
我在这里尝试了类似问题的解决方案:Why does data returned from coredata become nil after tableview scroll in swift? ,但这没有用。但是,我确实相信这与异步 API 调用有关。
我认为可能的解决方案可能包括在生成单元格之前填充一组 API 数据,但在重新考虑代码的架构之前,我希望对这个问题的根源有一些了解。
最佳答案
您需要在 viewDidLoad
中进行 API 调用以了解那里有多少个元素并将它们的 ID 记录在一个数组中。然后在你的cellForRow
函数中,你可以通过这种方式获取id
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell
apiCaller.getAPIDataThroughAsyncCall(id: array[indexPath.row], entry: { cellContent in
DispatchQueue.main.async(execute: {
...
})
})
return cell
}
您的 nextCell 无法工作的原因是,每次当您的 TableView 试图显示当前不在屏幕上的单元格时,都会调用此 cellForRow
函数。假设您知道您有 10 个元素,而您的屏幕只能显示其中的 5 个。当您滚动到底部时,您的 nextCell 将变为 10 并且一切正常。但是现在当你向上滚动时,表格 View 必须再次准备前 5 个。所以现在您的 nextCell 变为 15,您的 API 调用中没有对应的元素。
关于带有 Swift 的 iOS : App crashes on UITableView scroll down event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611369/