2017-02-03 45 views
0

當用戶在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

回答

1

請勿爲此使用標籤。 UITableView有一個函數indexPathForCell,它會給你indexPath。由於當你添加或刪除項目時,你的模型應該與你的tableView同步,你應該使用這個indexPath來索引數組。標籤很少有必要,通常是不好的做法。