Swift 仍然获取空数组时出错
我仍然在tableView中遇到错误,我无法找出原因:Swift 仍然获取空数组时出错,swift,uitableview,Swift,Uitableview,我仍然在tableView中遇到错误,我无法找出原因: @objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var productsToDisplay: [SKProduct]! override func viewWillAppear(_ animated: Bool) { // an assync call to load products to
@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var productsToDisplay: [SKProduct]!
override func viewWillAppear(_ animated: Bool) {
// an assync call to load products to the productsToDisplay
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else {
fatalError("Coulnd't parse table cell!")
}
// here the app always show an error without any specification
if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0)) {
return cell
}
cell.nameLabel.text = "my text"
return cell
}
}
我做错了什么?或者如何修复错误/在加载数据之前不加载表的内容
非常感谢基本上从不将数据源数组声明为(隐式展开)可选。将其声明为非可选空数组:
var productsToDisplay = [SKProduct]()
好处是非可选类型不能崩溃
在
numbersOfRows
中返回项目数:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productsToDisplay.count
}
如果数组为空,则永远不会调用cellForRow
在
cellForRow
中,首先设置标签,然后返回单元格并检查0,不需要nil
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as! PurchaseItemTableViewCell
let product = productsToDisplay[indexPath.row]
cell.nameLabel.text = product.name // change that to the real property in SKProduct
return cell
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell
在异步加载调用完成之前,系统不应调用
您必须实现func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int
,并让它返回产品中的元素数以显示
。只有在至少有一行要显示的情况下,系统才会调用cellForRowAt indexPath
异步请求完成后,请记住在
表视图上调用reloadData
。如果为零,则不会返回任何内容。使用部分tableview委托方法中的numberOfRows并返回productsToDisplay.count.抱歉,它在那里,我只是没有复制it@David为了安全起见,您应该返回productsToDisplay?.count??0
。