我正在尝试向静态表中添加一行,但出现此错误:
2015-05-31 13:53:13.153 notify[30565:6091085] *** 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*** -[__NSArrayI objectAtIndex:]:索引 2超出范围 [0 .. 1]'
我有一个@IBAction(连接到一个UINavigationItem)来添加行:
@IBAction func addRow(sender: AnyObject) {
let indexPath = NSIndexPath(forRow: rowCount, inSection: 0)
rowCount += 1
rowAdded = true
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
带有 rowCount 的属性(在 IB 设计中是默认的),以及一个用于判断是否已添加下一行的 bool 值:
class NotifyTableViewController: UITableViewController {
var rowCount = 2
var rowAdded = false
...
}
表格有 1 个部分,我添加的 numberOfRowsInSection:
方法:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if rowAdded {
return 3
}else {
return 2
}
}
最后,cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 2 {
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("customCell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "customCell")
cell.textLabel!.text = "New Cell"
}
return cell
}else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
我尝试将 insertRowsAtIndexPaths 调用包装在 begin/endUpdates 中,但我遇到了同样的错误。知道问题出在哪里吗?
最佳答案
好的,要将行添加到静态表我还需要实现
intentationLevelForRowAtIndexPath:
和 heightForRowAtIndexPath:
override func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.row == 2 {
let path = NSIndexPath(forRow: 0, inSection: indexPath.section)
return super.tableView(tableView, indentationLevelForRowAtIndexPath: path)
}
return super.tableView(tableView, indentationLevelForRowAtIndexPath: indexPath)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 2 {
return 42
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
关于ios - 在静态 UITableView 上插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557781/