我正在 Swift 中制作一个待办事项应用程序,并且尝试使用UITableView显示任务。用户添加任务,然后按“完成”。UITableView返回到前面,应用程序崩溃。这是我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil) //crashes on this line
cell.textLabel!.text = taskMgr.tasksArray[indexPath.row].name
cell.detailTextLabel!.text = taskMgr.tasksArray[indexPath.row].desc
return cell
}
有趣的是,这条线在我快速创建的另一个非常相似的应用程序中运行良好。有人能指出我正确的方向吗?如果有必要,我很乐意添加更多细节。
我是这样写的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
cell.lblText.text = "Testing"
return cell
}
使用重用标识符
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tblSwift.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
带详细标题
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
cell!.textLabel.text = self.names[indexPath.row]
cell!.detailTextLabel.text = self.emails[indexPath.row]
return cell
}
您应该重构代码以利用 UITableView 的性能。您的单元格可以重复使用,而不是每次在屏幕上显示时都重新创建。
为此,您应该删除 UITableViewCell 的 init 方法调用。而是将其替换为: dequeueReusableCellWithIdentifier:forIndexPath:
iOS 6 中的新模式是使用重用标识符向 tableview 注册 TableViewCell 子类。然后您可以使用 dequeReusableCellWithIdentifier:forindexPath 轻松获取可重用单元格:
在viewDidLoad
调用表视图数据源/委托方法之前或之前的某个地方,您应该调用来注册您的单元格子类。 注册类:用于CellReuseIdentifier:
对于您来说,在 Swift 中,您需要调用:
tableview.registerClass(UITableViewCell.self, identifier:"MyReuseIdentifier")
// note there is also a method to register nibs
然后在cellForRowAtIndexPath方法中:
tableView.dequeReusableCellWithIdentifier("MyReuseIdentifier", forIndexPath: indexPath)
为什么不通过 cellidentifier 重复使用单元格?
你真的不需要盲目飞行。当应用程序崩溃时,查看堆栈,检查是否有错误消息。如果应用程序超出了实际错误,请在所有异常上添加符号断点。如果您看到抛出异常,请打印该异常。在开始开发之前,您需要学习如何使用调试工具来获取更多信息的基础知识。这比发布到 SO 快得多。
“细胞”从何而来?我正在尝试做同样的事情,但是使用自定义表格视图,其中包含类似于操作系统设置中的部分,您可以在其中提供一个选项列表,其中包含附近的另一个 WiFi 点列表。
我的程序仍然崩溃tableView.dequeReusableCellWithIdentifier("MyReuseIdentifier", forIndexPath: indexPath)。
有错误信息或者日志吗?'tableView' 或 indexPath 是否有可能为零(这真的很奇怪)?