在静态UITableView上插入行

时间:2015-05-31 13:06:32

标签: ios uitableview swift

我试图在静态表中添加一行,但是我收到了这个错误:

2015-05-31 13:53:13.153 notify[30565:6091085] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds [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)
    }
}

我尝试在begin / endUpdates中包装insertRowsAtIndexPaths调用,但是我得到了同样的错误。知道问题是什么吗?

1 个答案:

答案 0 :(得分:0)

好的,要将行添加到静态表中,我还需要实现 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)
}