使用标签检索TableView中的数据的问题

问题描述:

当用户在tableView单元格内按下按钮时,我需要从tableView填充的数组中获取单元格的数据。将这些数据用于某些单元格后,将其从tableView中删除。使用标签检索TableView中的数据的问题

我正在使用标签来了解按钮被按下的单元格的索引。但是,一旦tableView中间的单元格与数组中的数据一起被删除,那么tableView下方的单元格现在具有标签超出数组边界的按钮。例如:

array.length = 3 
  • 小区0(按钮标签:0)
  • 小区1(按钮标签:1)
  • 小区2(按钮标签:2)

用户然后按下单元格1内的按钮,然后将其从阵列和表中移除:

  • 单元格0(按钮标签:0)
  • 细胞2(纽扣标签:2)

现在的问题是,如果用户按下电池2,当我尝试使用标签的应用程序会崩溃从阵列中获得该单元格的数据因为我正在访问一个越界索引。因此,我开始认为使用标签不是一个好的选择,我想知道什么是更好的选择。这里是我的代码:

var invitesArray = [userInfo]() 

func declineInvite(sender: UIButton!) { 
    let info = invitesArray[sender.tag] 
    // I use info to process data 

    // Remove cell's data from array and remove cell from table 
    inviteTable.beginUpdates() 
    inviteTable.deleteRows(at: [IndexPath(row: sender.tag, section: 0)], with: UITableViewRowAnimation.automatic) 
    invitesArray.remove(at: sender.tag) 
    inviteTable.endUpdates() 
} 

// Populating the tableView 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = inviteTable.dequeueReusableCell(withIdentifier: "inviteCell", for: indexPath) as! joinCell 
    cell.declineButton.tag = indexPath.row 
    cell.declineButton.addTarget(self, action: #selector(self.declineInvite), for: UIControlEvents.touchUpInside)  
    return cell 
} 

任何人都可以帮助纠正我的天真方式吗?

+0

使用基于行号的标签仅适用于不能插入,移除或移动行。 – rmaddy

+0

是的我明白,因此这个问题 – MarksCode

+0

可能重复的[swift:如何获取indexpath.row当单元格中的按钮被点击?](http://stackoverflow.com/questions/28659845/swift-how-在单元格被点击时获取该索引路径行) – Shades

请勿为此使用标签。 UITableView有一个函数indexPathForCell,它会给你indexPath。由于当你添加或删除项目时,你的模型应该与你的tableView同步,你应该使用这个indexPath来索引数组。标签很少有必要,通常是不好的做法。