swiftmacosnstableviewnstablecellview

delete and add row in view Based NSTableView


I did IOS development but new to OSX. I am facing problem that I delete the row in NStableView successfully by clicking the button in row of table but when I click on add button the deleted row appears again and then its not deleted. Here is my delete function

   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 is basically variable which I increment when row is added and decrement when row is deleted respectively. My adding Row function is

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

And data source is

  func numberOfRows(in tableView: NSTableView) -> Int
{
  return rowCount
}

Solution

  • Do not assign tags to buttons in an NSTableView

    NSTableView provides a very convenient way to get the current row: The method

    func row(for view: NSView) -> Int


    The code in the action can be reduced to 3 lines

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

    To add a row, append a value to the data source array and then call insertRows

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

    Note:

    Never call reloadData after insert- / removeRows. You get rid of the animation and the insert / remove methods do update the UI. The methods beginUpdates and endUpdates are useless for a single insert / move / remove operation.