代码之家  ›  专栏  ›  技术社区  ›  Ahmed Khan

在基于NtableView的视图中删除和添加行

  •  2
  • Ahmed Khan  · 技术社区  · 8 年前

    我做过IOS开发,但对OSX还不熟悉。我面临的问题是,我通过单击表格行中的按钮成功删除了NStableView中的行,但当我单击“添加”按钮时,删除的行再次出现,然后未删除。 这是我的删除功能

       func delIssue(_ sender:NSButton)
    {
      let btn = sender
      if btn.tag >= 0
      {
        let issueValue = issueKeys[btn.tag]
        for index in 0..<issueName.count
        {
          if issueValue == issueName[index]
          {
            issueName.remove(at: index)
    
            rowCount = rowCount - 1
            self.tableView.removeRows(at: NSIndexSet.init(index: index) as IndexSet , withAnimation: .effectFade)
            self.tableView.reloadData()
            break
          }
        }
      }
    }
    

    rowCount基本上是可变的,当行被添加时,它会增加,当行被删除时,它会减少。 我的添加行函数是

        @IBAction func addRow(_ sender: Any)
      {
        rowCount += 1
        DispatchQueue.main.async
        {
          self.tableView.reloadData()
        }
      }
    

    数据源为

      func numberOfRows(in tableView: NSTableView) -> Int
    {
      return rowCount
    }
    
    2 回复  |  直到 8 年前
        1
  •  4
  •   vadian    8 年前

    不要将标签指定给列表中的按钮 NSTableView

    NSTableView 提供了一种非常方便的获取当前行的方法:

    func row(for view: NSView) -> Int


    操作中的代码可以减少到3行

    @IBAction func delIssue(_ sender: NSButton)
    {
      let row = tableView.row(for: sender)
      issueName.remove(at: row)
      tableView.removeRows(at: IndexSet(integer: row), withAnimation: .effectFade)
    }
    

    要添加行,请将值附加到数据源数组,然后调用 insertRows

    @IBAction func addRow(_ sender: Any)
    {
        let insertionIndex = issueName.count
        issueName.append("New Name")
        tableView.insertRows(at: IndexSet(integer:insertionIndex), withAnimation: .effectGap)
    }
    

    注:

    从不打电话 reloadData 之后 insert- / removeRows . 删除动画后,插入/删除方法会更新UI。方法 beginUpdates endUpdates 对于单个插入/移动/删除操作无效。

        2
  •  0
  •   Ahmed Khan    8 年前

    最后,我发现可以正确删除行,这就是我如何做到的

     self.tableView.beginUpdates()
        self.tableView.removeRows(at: indexSet , withAnimation: .effectFade)
        self.tableView.endUpdates()