ios - 在静态 UITableView 上插入行

标签 ios uitableview swift

我正在尝试向静态表中添加一行,但出现此错误:

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/

相关文章:

iphone - Monotouch : Get x. y 或点击 UIView

ios - 得到无法识别的选择器 -replacementObjectForKeyedArchiver : crash when implementing NSCoding in Swift

Swift 5 LLDB 错误 : warning: <EXPR>:12:9: warning: initialization of variable '$__lldb_error_result' was never used

iphone - 在 UItableView EditingStyle Delete 中拯救单元格的问题

ios - 仅一种原型(prototype)单元格的自动表格 View 单元格高度

ios - 为什么我在 Xcode 中的一个文件消失了?

iOS - 解析登录 - 更改按钮标题

android - Flutter List<Dynamic> 应该是 List<DataRow>

ios - 如何在 Swift 中通过 'startAccessingSecurityScopedResource()' 进行 throw 声明?

swift - 布局 subview 或约束?