我有UITableView,而竞赛是动态原型。
所以我有5个单元格,每个单元格都有自己的标识符。 所以当我尝试返回(cellForRowAt)中的值时 它会让我。
请帮忙吗?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section) == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell!
// cell?.textLabel!.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]
return cell!
}
else if (indexPath.section) == 2 {
let cell3 = tableView.dequeueReusableCell(withIdentifier: "cellThree") as UITableViewCell!
return cell3!
}
else if (indexPath.section) == 3 {
let cell4 = tableView.dequeueReusableCell(withIdentifier: "cellFour") as UITableViewCell!
return cell4!
}
else if (indexPath.section) == 4 {
let cell5 = tableView.dequeueReusableCell(withIdentifier: "cellFive") as UITableViewCell!
return cell5!
}
return cell!
}
谢谢!
新更新: -
所以向我显示的错误是(使用未解析的标识符'cell') 所以,当我最后返回(返回单元格!)时,它显示此错误。但是,如果我删除该行,它会显示另一个错误,要求我返回一个值
所以底线我确定应该在(cellForRowAt)结束时返回什么值。
答案 0 :(得分:0)
编辑:我刚刚意识到您没有使用for indexPath
中的dequeueReusableCellWithIdentifier
参数。使用它,否则它是错误的。见:
https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecellwithidentifie
https://www.natashatherobot.com/ios-using-the-wrong-dequeuereusablecellwithidentifier/
@Nawaf您无法从任何函数返回多个值,因此您无法通过cellForRow
的一次调用返回多个单元格。您可能误解了cellForRowAtIndexPath
的工作原理。现在你的代码没有填充单元格中的任何内容。
使用未解析的标识符'cell'
此外,您的错误可能由于多种原因而发生。例如,检查您的视图控制器是否已正确分配到故事板中的视图控制器,并且您已在故事板中分配了reuseIdentifier。
有关详细信息,请参阅链接: https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614861-tableview?language=objc
How does cellForRowAtIndexPath work?
也是代码质量的旁注:不要强制转换为单元格,因为这可能会导致意外错误。改为使用条件绑定:
guard let cell = tableView.dequeueReusableCellWithIdentifier(...) as? UITableViewCell else {
// What to do when the cast failed
}
答案 1 :(得分:0)
此方法每次调用时只能返回一个单元格。每当新单元格即将出现在屏幕上时,将调用该方法。看一下方法签名:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
最后UITableViewCell
是预期的返回值,在这种情况下,它是一个单元格。
让我们来看看你的错误:
使用未解析的标识符'cell'
“未解析的标识符”表示它不知道什么是“单元格”,因为它尚未在当前范围中声明。但是你不是在这个方法中声明cell
吗?是的,但是他们在一个单独的范围内。变量范围定义变量的存在时间以及可以看到的位置。当您看到一组新的大括号{}
时,您可以判断何时声明了新的变量作用域,每个if
语句都会声明。在每组花括号中声明的变量只能通过这些括号中包含的代码来查看。一旦执行离开那些括号,那些变量就消失了。让我们通过删除return
语句创建的范围来查看最终if
语句范围内可查看的变量:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cell!
}
现在很明显,返回时cell
不存在。您需要在方法的范围中声明cell
并为其赋予一些值。请注意,强制解包单元格选项可能会导致运行时崩溃,因为该方法不能返回nil
。当tableView.dequeueReusableCell()
返回nil
时,您需要创建单元格。