Search code examples
iosswiftscrolltableviewfade

How would I fade in cells as they load?


Currently I'm utilizing a class with this method.

class TipInCellAnimator {
// placeholder for things to come -- only fades in for now
class func animate(cell:UITableViewCell) {
    let view = cell.contentView
    view.layer.opacity = 0.1
    UIView.animateWithDuration(0.1) {
        view.layer.opacity = 1
    }
}
}

And invoking it in my main viewcontroller as follows

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
       forRowAtIndexPath indexPath: NSIndexPath) {
            TipInCellAnimator.animate(cell)
    }

The problem I have is that the cells flash when items are reloaded and as it is fading in and I cant tap on the screen to stop the scrolling.

Does anyone have some tips on how to fix these issues or other methods of achieving the same effect?


Solution

  • By looking at your code, the most obvious reason for "flashing" of the cells is because of the duration of your animation. Try to increase the duration from 0.1 to something like 0.5

    For the second question, iOS by default ignores user interaction when its view is animating. To enable this, set the options in UIViewAnimationOptions to "AllowUserInteraction".

    Please refer the following code for Swift 1.2

    class func animate(cell:UITableViewCell) {
            let view = cell.contentView
            view.layer.opacity = 0.1
            UIView.animateWithDuration(0.5, delay: 0, options: .AllowUserInteraction | .CurveEaseInOut, animations: { () -> Void in
                view.layer.opacity = 1
                }, completion: nil)
    }
    

    Or in Swift 2.0

    class func animate(cell:UITableViewCell) {
            let view = cell.contentView
            view.layer.opacity = 0.1
            UIView.animateWithDuration(0.5, delay: 0, options: [.AllowUserInteraction, .CurveEaseInOut], animations: { () -> Void in
                view.layer.opacity = 1
                }, completion: nil)
    }