Mala D'Suza
Mala D'Suza

Reputation: 1

pangesture in UItableviewcell, table scroll is not working in swift

I want to swipe UIview left and right inside the UItableviewCell, And I have used UIPanGestureRecognizer to make this happen and below is the attached source code. However when I am trying to scroll UItableview my Uiview is moveable up and down and unable to give scroll to UItableviewcell i.e Superview.Can anyone tell me how to manage? Thanks in advance?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 10

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "CardSwipeTVCell") as! CardSwipeTVCell


    let tapGesture : UIPanGestureRecognizer!
    tapGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.tapEdit(_:)))
    cell.cardView.addGestureRecognizer(tapGesture!)
    cell.cardView.tag = indexPath.row
    tapGesture!.delegate = self


    cell.selectionStyle = .none
    return cell


}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


}

func tapEdit(_ recognizer: UIPanGestureRecognizer)
{
    print(recognizer.view?.tag as Any)

    let sender = recognizer.view?.tag as Any

    let indexPath = IndexPath(row: sender as! Int, section: 0)
    let cell = self.cardTableView.cellForRow(at: indexPath) as? CardSwipeTVCell


    cell?.cardView.backgroundColor = UIColor.black

    let card = recognizer.view!
    let point = recognizer.translation(in: view)
    card.center = CGPoint(x: (cell?.center.x)! + point.x, y: (cell?.center.y)! + point.y)

    if recognizer.state == UIGestureRecognizerState.ended
    {
        UIView.animate(withDuration: 0.3, animations: {

            card.center = (cell?.center)!

        })

    }

}

Also another problem is when I tap on the second cell my view got disappeared? Your help will really appreciated.

Upvotes: 0

Views: 1357

Answers (1)

Pravin Kulkarni
Pravin Kulkarni

Reputation: 263

override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
    if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
        //let translation = panGestureRecognizer.translation(in: superview!)
        let translation = panGestureRecognizer.translationInView(superview)
        if fabs(translation.x) > fabs(translation.y) {
            return true
        }
        return false
    }
    return false
}

Add above delegate method in your class. which will stop pangesture while tableview view scrolling vertically.

Upvotes: 4

Related Questions