Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

How can I animate any UIView inside UITableViewCell?

let label = UILabel(frame: CGRectMake(20.0, 20.0, 15.0, 15.0))
label.backgroundColor = UIColor.flamingoColor() 

UIView.animateWithDuration(3.0, animations: {
    cell.addSubview(label)
    label.backgroundColor = UIColor.yellowColor()
})

This code I put inside tableView:cellForRowAtIndexPath: -> result is a subview that has a yellow background, but I haven't seen any animation. The same is for method tableView:didEndDisplayingCell:

Which method should I use or what kind of animation should I put there to see any animations inside UITableViewCell. I know that I cannot animate existing labels, because these are with constraints.

Upvotes: 2

Views: 2231

Answers (1)

ABakerSmith
ABakerSmith

Reputation: 22939

Firstly, you should move cell.addSubview(label) to outside of the animation block and add the label to the contentView of the cell.

Back to your problem. You can't animate the background colour of a UILabel. You could use a UIView, of the same size, behind the UILabel for the same effect though.

To get the UIView to change colour once it's appeared I used a UITableViewCell subclass:

class AnimatedCell : UITableViewCell {
    let animatedView = UIView()

    /*  Setup by adding animatedView to the contentView and setting the 
        animated view's initial frame and colour.
    */

    func animate() {
        UIView.animateWithDuration(3.0) {
            animatedView.backgroundColor = UIColor.redColor() 
        }
    }

Then in your UITableViewController subclass, when the view controller is presented the UITableView will be populated so you need to animate those cells with:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: Bool)

    for cell in tableView.visibleCells() as! [UITableViewCell] {
        if let animatedCell = cell as? AnimatedCell {
            animatedCell.animate()
        }
    }
}

Then, for cells that appear when you scroll:

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if let animatedCell = cell as? AnimatedCell {
        a.animateLabel()
    }
}

Also, you can animate with AutoLayout, you need to change the constant on the NSLayoutConstraint you want to animate. This gives a good example: iOS: How does one animate to new autolayout constraint (height)

Upvotes: 1

Related Questions