How to move UITableViewCell back and forth to show it can be swiped?

前端 未结 2 975
日久生厌
日久生厌 2021-02-19 13:49

I see in some apps when you come to a screen with a tableview there\'s a short animation of the cell starting to be swiped, showing the red \"swipe to delete\" button (UIContext

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 14:01

    Swift Solution

    Well, about 1.5 years later I finally came up with a solution.

    Step 1 - Cell UI Setup

    I set up my custom table view cell like this:

    • A and B represent the swipe action colors.
    • C is the UIView that I will animate side-to-side.

    Step 2 - Add Animation to Cell

    func animateSwipeHint() {
        slideInFromRight()
    }
    
    private func slideInFromRight() {
        UIView.animate(withDuration: 0.5, delay: 0.3, options: [.curveEaseOut], animations: {
            self.cellBackgroundView.transform = CGAffineTransform(translationX: -self.swipeHintDistance, y: 0)
            self.cellBackgroundView.layer.cornerRadius = 10
        }) { (success) in
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
                self.cellBackgroundView.transform = .identity
            }, completion: { (success) in
                // Slide from left if you have leading swipe actions
                self.slideInFromLeft()
            })
        }
    }
    
    private func slideInFromLeft() {
        UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseOut], animations: {
            self.cellBackgroundView.transform = CGAffineTransform(translationX: self.swipeHintDistance, y: 0)
        }) { (success) in
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
                self.cellBackgroundView.transform = .identity
            })
        }
    }
    

    Step 3 - Trigger the Animation

    In the viewDidLoad of the view controller that has the table view, I have this code:

    if self.tableView.visibleCells.count > 0 {
        let cell = self.tableView.visibleCells[0] as! TableViewCell
        cell.animateSwipeHint()
    }
    

    Example:

    Video Solution

    I created a video if you'd like a more in-depth walkthrough of this solution: https://youtu.be/oAGoFd_GrxE

提交回复
热议问题