Home > Back-end >  UITableView cells animation on scroll. Swift
UITableView cells animation on scroll. Swift

Time:05-22

Community, please help out a beginner! Can you tell me how to make such animation for TableView cells? Thank!

cell animation as in this video with Swift

CodePudding user response:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let rotationTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 100, 0)
        cell.layer.transform = rotationTransform
        
        UIView.animate(withDuration: 0.05 * Double(indexPath.row)) {
            cell.layer.transform = CATransform3DIdentity
        }
    }

if this one a UItableViewController add override before func as: override func tableView(_ tableView: UITableView....

CodePudding user response:

This gives something similar to what you want. You might need to make adjustments to it or improve the code snippet. You can work with the panGestureRecognizer property of the tableView

tableView.panGestureRecognizer.addTarget(self, action: #selector(didPan(_:)))

With this handler:


    @objc func didPan(_ gesture: UIPanGestureRecognizer) {
        guard gesture.state == .changed else { return }

        let loc = gesture.location(in: tableView)
        guard let touchedCellIndex = tableView.indexPathForRow(at: loc) else { return }
        let n = tableView.numberOfRows(inSection: 0)
        guard touchedCellIndex.row < n - 1 else { return }
        
        if gesture.translation(in: tableView).y < 0 {
            for (index, cell) in tableView.visibleCells.enumerated() {
                guard let ip = tableView.indexPath(for: cell) else { return }
                if ip.row > touchedCellIndex.row {
                    cell.transform = CGAffineTransform(translationX: 0.0, y: -gesture.velocity(in: tableView).y * 0.02 * tanh(CGFloat(index)))
                    UIView.animate(withDuration: 0.05 * Double(index), delay: 0.0) {
                        cell.transform = CGAffineTransform.identity
                    }
                }
                
            }
        } else {
            for (index, cell) in tableView.visibleCells.reversed().enumerated() {
                guard let ip = tableView.indexPath(for: cell) else { return }
                if ip.row < touchedCellIndex.row {
                    cell.transform = CGAffineTransform(translationX: 0.0, y: -gesture.velocity(in: tableView).y * 0.02 * tanh(CGFloat(index)))
                    UIView.animate(withDuration: 0.05 * Double(index), delay: 0.0) {
                        cell.transform = CGAffineTransform.identity
                    }
                }
                
            }
        }
    }
     

I am sure you can optimize this approach and make it more concise.

  • Related