删除并添加视图中的行基于NSTableView

时间:2018-01-02 13:23:57

标签: swift macos nstableview nstablecellview

我做了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 个答案:

答案 0 :(得分:4)

请勿为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)
}

注意:

切勿在{{1​​}}之后致电reloadData。你摆脱了动画,插入/删除方法确实更新了UI。方法insert- / removeRowsbeginUpdates对于单个插入/移动/移除操作无用。

答案 1 :(得分:0)

最后我发现正确删除行,这就是我做的方式

 self.tableView.beginUpdates()
    self.tableView.removeRows(at: indexSet , withAnimation: .effectFade)
    self.tableView.endUpdates()
相关问题