2016-04-07 31 views
1

我使用UITableViewController.swift和UITableViewCell.swift構建了一個包含CoreData的應用程序。在TableViewCell中刪除行後在TableViewController中刪除行

我試圖通過在UITableViewCell.swift中使用UIPanGestureRecognizer來刪除行,如同在Clear to-do應用程序中一樣。我可以平移行左側和右側,但我不知道如何獲得這些選定行的indexPath,並在所有數據所在的UITableViewController.swift中將其刪除。

EduDicTableViewCell.swift:

override func awakeFromNib() { 
    super.awakeFromNib() 

    let recognizer = UIPanGestureRecognizer(target: self, action: #selector(EduDicTableViewCell.handlePan(_:))) 

    recognizer.delegate = self 
    addGestureRecognizer(recognizer) 
} 

//MARK: - horizontal pan gesture methods 
func handlePan(recognizer: UIPanGestureRecognizer) { 
    // 1 
    if recognizer.state == .Began { 
     // when the gesture begins, record the current center location 
     originalCenter = center 
    } 
    // 2 
    if recognizer.state == .Changed { 
     let translation = recognizer.translationInView(self) 
     center = CGPointMake(originalCenter.x + translation.x, originalCenter.y) 
     // has the user dragged the item far enough to initiate a delete/complete? 
     deleteOnDragRelease = frame.origin.x < -frame.size.width/2.0 
    } 
    // 3 
    if recognizer.state == .Ended { 
     let originalFrame = CGRect(x: 0, y: frame.origin.y, 
            width: bounds.size.width, height: bounds.size.height) 
     if deleteOnDragRelease { 
      print("send it") 



     } else { 
      UIView.animateWithDuration(0.2, animations: {self.frame = originalFrame}) 
      print("Bounced Back") 
     } 
    } 
} 

感謝您的閱讀!

回答

1

你可以在你的自定義單元格,這就要求在表視圖控制器適當的方法使用委託/協議:

協議定義添加到單元格:

protocol EduDicTableViewCellDelegate { 
    func didSwipeDelete(cell: UITableViewCell) 
} 

,然後添加(可選)delegate變量與此協議:

var delegate : EduDicTableViewCellDelegate? = nil 

handlePan方法,添加一條線來調用委託方法當泛發佈:

if deleteOnDragRelease { 
    print("send it") 
    self.delegate?.didSwipeDelete(self) 
} else ... 

注意,didSwipeDelete方法傳遞self - 這是刷卡的細胞。

在表格視圖控制器,添加方法刪除的細胞(使用的tableView的indexPathForCell方法來獲得對應於這是刷卡該小區的indexPath):

func didSwipeDelete(cell: UITableViewCell) { 
    if let indexPath = self.tableView.indexPathForCell(cell) { 
     print("didSwipeDelete \(indexPath.section) - \(indexPath.row)") 
     // remove the object at this indexPath from the data source 
     // and delete the corresponding table view row 
     ... 
    } 
} 

修改該表的類定義視圖控制器,以表明它採用的協議:

class CustomTableViewController: UITableViewController, EduDicTableViewCellDelegate { 
    ... 
} 

最後,在cellForRowAtIndexPath方法,對細胞設置delegate變量self(表VI ew控制器):

cell.delegate = self 
+0

這是完美的!感謝數百萬! –

+0

非常好。謝謝! – Ibrahim