gpt4 book ai didi

ios - 用 if var 解开并仍然返回单元格

转载 作者:行者123 更新时间:2023-11-30 12:26:46 25 4
gpt4 key购买 nike

我在 UITableViewController 类中有一个 cellForRowAt indexPath 方法,我试图在其中解开变量“tasks”(在另一个 .swift 文件中声明)。如果我用 if var 解开它,然后返回 if var 范围之外的单元格,我会得到一个“使用未解析的标识符‘单元格’”错误,但是如果我在 if var 范围内包含返回单元格,我会得到一个“预期返回‘UITableViewCell’的函数中缺少返回”错误。我该如何解决?我刚刚学习 Swift,所以任何帮助将不胜感激。谢谢!

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if var tasks = exampleList.tasks {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
let task = tasks[indexPath.row]
cell.task = task

if cell.accessoryView == nil {
let cb = CheckButton()
cb.addTarget(self, action: #selector(buttonTapped(_:forEvent:)), for: .touchUpInside)
cell.accessoryView = cb
}

let cb = cell.accessoryView as! CheckButton
cb.check(tasks[indexPath.row].completed) //Replaced previous cb.check line with this per Stack Overflow James Baxter's advice

}
return cell
}

最佳答案

我不确定这是否能解决您的问题,但您可以尝试以下操作:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if var tasks = exampleList.tasks {
cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
let task = tasks[indexPath.row]
cell.task = task

if cell.accessoryView == nil {
let cb = CheckButton()
cb.addTarget(self, action: #selector(buttonTapped(_:forEvent:)), for: .touchUpInside)
cell.accessoryView = cb
}

if let cb = cell.accessoryView as! CheckButton {
cb.check(tasks[indexPath.row].completed) //Replaced previous cb.check line with this per Stack Overflow James Baxter's advice
}

}
return cell
}

请记住,tableView 函数必须始终返回一个 UITableViewCell 对象,因此即使第一个 if 语句失败,您也必须提供有效的返回!阅读 Apple 关于可选值、展开等的文档。祝你好运!

关于ios - 用 if var 解开并仍然返回单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44099031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com