Search code examples
iosswiftuitableviewcore-animation

How to animate insert sections from bottom of screen


I need to do an animation in UITableView to insert sections but i need the sections to animate from the bottom of the screen.

And not like one of the default UITableViewRowAnimation animations.

This is animation i need:

Animation description

Any suggestions?

Thanks


Solution

  • I figured out how to do this with a simple solution.

    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
        if shouldAnimate {
            cell.alpha = 0
            let transform = CATransform3DTranslate(CATransform3DIdentity, 0, UIScreen.main.bounds.height, 0)
            cell.layer.transform = transform
    
            UIView.animate(withDuration: 0.5, animations: {
                cell.alpha = 1
                cell.layer.transform = CATransform3DIdentity
            })
        }
    }
    
    public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if shouldAnimate {
            view.alpha = 0
            let transform = CATransform3DTranslate(CATransform3DIdentity, 0, UIScreen.main.bounds.height, 0)
            view.layer.transform = transform
    
            UIView.animate(withDuration: 0.5, animations: {
                view.alpha = 1
                view.layer.transform = CATransform3DIdentity
            })
        }
    }
    
    public func addSections(sections: IndexSet) {
        shouldAnimate = true
        CATransaction.begin()
        CATransaction.setCompletionBlock({ self.shouldAnimate = false })
    
        tableView.beginUpdates()
        tableView.insertSections(sections, with: .top)
        tableView.endUpdates()
    
        tableView.scrollToRow(at: IndexPath(row: 0, section: 1), at: .top, animated: true)
    
        CATransaction.commit()
    }
    

    So willDisplay cell/header handles the animation from the bottom of the screen.

    shouldAnimate cancels the cells animations after finishing the insertSection