将表视图出口作为cellForRowAtindexPath中的参数传递



我在视图控制器的textFieldShouldReturn中手动调用cellForRowAtindexPathcellForRowAtindexPath的参数是tableViewOutletindexPath(本例中为"index")。这里cellForRowAtindexPathtableViewOutlet都来自另一个视图控制器,我使用实例调用它们。

一旦cellForRowAtindexPath调用它显示错误,如:

在展开可选值时意外发现nil。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if(textField == carRating){
let rating = Float(textField.text!)
secondInstanceForMyData.masterCarData[index.row].carRating = rating
let _: MyTableViewCell = myViewControllerInstance.tableView(myViewControllerInstance.tableViewWillLoad as UITableView, cellForRowAt: index) as! MyTableViewCell
}
return true
}

您在这里调用的是表视图数据源方法tableView(tableView:cellForRowAt:),它永远不应该由您调用,它必须由您实现。这样想吧,这种方法需要为表视图提供一个单元格,而不是要求它

如果要从已填充的表视图中获取单元格,请调用表视图方法cellForRow(at:)

let indexPath = IndexPath(row: 0, section: 0)
if let cell = tableView?.cellForRow(at: indexPath) as? MyTableViewCell {
// do something with the cell
}

如果要更新表视图,则需要更新数据源,并在表视图上调用reloadData()或调用其中一个更新方法。

最新更新