Aar*_*You 3 uitableview ios swift
我是 iOS 编程领域的新手,最近在网上看到了一些实现的代码示例,例如:
\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { \n var cell = tableView.dequeueReusableCell(withIdentifier: customCellIdentifier, for: indexPath) as? CustomCell\n if (cell == nil) {\n cell = CustomCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: customCellIdentifier) asCustomCell\n }\n ...\n }\nRun Code Online (Sandbox Code Playgroud)\n作者试图处理dequeueReusableCellreturn nil 的事件。
dequeueReusableCell但从我对 UITableView 和自定义单元格的有限个人经验来看,我还没有遇到过返回 nil 的情况。
经过研究,我发现原因可能是
\n\n\n\n“dequeue\xe2\x80\xa6 方法尝试查找当前位于屏幕外的具有给定重用\n标识符的单元格。如果找到,则返回\n该单元格,否则返回 nil。”
\n
但这种事从来没有发生在我身上。当我故意给它一个错误的标识符时,会发生运行时错误,但不会返回 nil 一次。我想知道这种情况到底什么时候会发生以及是否真的有必要处理它。
\n该代码不正确。当重用池中没有可用单元格时(即当表视图首次出现时),dequeueReusableCell不带参数的旧形式indexPath将返回。nil在这种情况下,您有责任分配单元格。
您的问题中显示的较新形式dequeueResuableCell将始终返回一个单元格,因为它会根据需要分配一个单元格。
nil如果条件向下转换失败(即返回的单元格不是 的实例),问题中的表达式可能会返回CustomCell。
我认为这代表了某个地方的严重错误配置,应该在开发过程中发现。因此,通常使用强制向下铸造;在开发过程中,您会遇到崩溃,解决问题并继续。
let cell = tableView.dequeueReusableCell(withIdentifier: customCellIdentifier, for: indexPath) as! CustomCell
Run Code Online (Sandbox Code Playgroud)
你问题中的代码是某种新旧弗兰肯斯坦的混合体。
| 归档时间: |
|
| 查看次数: |
1093 次 |
| 最近记录: |