2016-03-31 157 views
0

基本上,我有一個自定義表格視圖單元格列出了潛在的員工。這個單元格包含一些標籤和一個按鈕。我想是的按鈕來刪除單元格,但所有我能找到的是:在表格視圖單元格中使用按鈕出列單元格

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
if editingStyle == UITableViewCellEditingStyle.Delete { 
    numbers.removeAtIndex(indexPath.row)  
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
} 

}

只允許你刪除單元格,如果你輕掃,然後選擇「刪除」

我想我應該在我的tableViewController.swift文件中創建一個函數,它將刪除給定行處的單元格,並在我的自定義單元格類中創建一個將調用該函數的IBAction。

在給定的行刪除單元格的函數是什麼樣的?但是在這種情況下,單元格是否也知道它在哪個行或者是tableViewController的作業?

+0

看到這個:http://stackoverflow.com/questions/8983094/how-to-enable-swipe-to-delete-cell-in-a-tableview – Koen

回答

1
  1. 在你cellForRowAtIndexPath設置cell.button.tag = indexPath.row

  2. 添加目標按鈕:在你的dataArray索引button.tagcell.button addTarget:...

  3. 在按鍵方法,刪除該項目。然後刷新的tableView self.tableView reloadData

1

可以使用的UIButton的標籤屬性來存儲您要刪除,並使用該標籤屬性的處理程序,以找到正確的電池單元的指標。在我的示例代碼中,我只是假設 ,您只有一個部分是它被設置爲零的原因。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    ... 
    ... 
    cell.button.tag = indexPath.row 
    let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleDeleteTap:")) 
    cell.button.addGestureRecognizer(tapGesture) 

} 

func handleDeleteTap(sender: UITapGestureRecognizer) 
{ 
    if let button = sender.view as? UIButton 
    { 
    let indexPath = NSIndexPath(forRow: button.tag, inSection: 0) 
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
    } 
} 
1

1)你必須cellForRowAtIndexPath定義您的按鈕動作:

... 
myButton.addTarget(self, action: "buttonTappedDelete:", forControlEvents: .TouchUpInside) 
... 

2)你必須實現選擇:
2.1)獲取其中的按鈕位於小區。
2.2)獲取單元格的索引路徑。
2.3)從表格視圖中刪除單元格並更新您的數據。

func buttonTappedDelete(sender: UIButton) { 
    let cell = sender.superview!.superview as! UITableViewCell 
    let indexPath = self.tableView.indexPathForCell(cell)! 
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
    // update your data model, call `self.tableView.reloadData()` 
} 
相關問題