mike vorisis
mike vorisis

Reputation: 2832

How to fade in/out the background color of a tableviewcell with Swift

I have a tableview and when I receive a message it reloads and then I want the cell that received the message to change its background color for a second and then change back to previous color (with or without fade in/out)

I know which cell received the message with that code:

    if changeCell == indexPath.row { 

         cell.viewCell.backgroundColor = UIColor.red 

    }

viewCell Is a view I put in cell to change the background color of the cell more easily

I search a lot to find it out but every solution started with UIView.animate.... when I put it it changed the color of the view outside my tableview

Upvotes: 1

Views: 2928

Answers (3)

Josh Homann
Josh Homann

Reputation: 16327

The UIView animate family of methods is what you want.

    let oldColor = cell.viewCell.backgroundColor
    UIView.animate(withDuration: 0.5, animations: {
        cell.viewCell.backgroundColor = UIColor.red
        }, completion: { _ in
            UIView.animate(withDuration: 0.5) {
                cell.viewCell.backgroundColor = oldColor
            }
    })

Upvotes: 4

Sean
Sean

Reputation: 721

I solved this by adding a UIImageView in the cell and setting the alpha of that. I couldn't get backgroundColor to animate.

Upvotes: 0

yoninja
yoninja

Reputation: 1962

Add these options for the animation:

  • UIViewAnimationOptions.transitionCrossDissolve
  • UIViewAnimationOptions.allowAnimatedContent

Example:

fileprivate var color1 = UIColor.clear
fileprivate var color2 = UIColor.red
fileprivate func animateCell(_ cell: UITableViewCell) {

    UIView.animate(withDuration: 1.0, delay: 0.0, options: [.transitionCrossDissolve, .allowAnimatedContent], animations: {
        cell.contentView.backgroundColor = self.color2
    }) { (_) in
        UIView.animate(withDuration: 1.0, animations: {
            cell.contentView.backgroundColor = self.color1
        })
    }

}

Upvotes: 3

Related Questions