2

I have this animation block, but the cell background color is clear immediately:

cell.mylabel.backgroundColor = .orange
UIView.animate(withDuration: 3.0, delay:3, animations: {
    cell.mylabel.backgroundColor = .clear
})

The point is I am running this in cellForRowAt

I tried moving animation to my custom cell, but no success again:

override func didMoveToWindow() {
            UIView.animate(withDuration: 3.0, delay:3, animations: {
                self.mylabel.backgroundColor = .clear
            })
    }
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210
  • 2
    Do the animation in `tableView:willDisplayCell:forRowAtIndexPath:` instead of `tableView:cellForRowAtIndexPath` – Eric Qian Sep 13 '16 at 05:40

2 Answers2

2

The point is I am running this in cellForRowAt

That is too early, because the cell may not be in the on-screen view hierarchy yet. You can only animate a view that's in the on-screen view hierarchy. You need to find a way to add the animation after the cell has been added as a subview of the table view.

I would create a custom UITableViewCell subclass. In the subclass, I would override didMoveToWindow to add the animation to self.

Alternatively, it might work to override viewDidLayoutSubviews in the table view controller (if it has one), and add the animation in that method.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

Try like this,

cell.mylabel.layer.backgroundColor = UIColor.redColor().CGColor
UIView.animate(withDuration: 3.0, delay:3, animations: {
    cell.mylabel.layer.backgroundColor = UIColor.clearColor().CGColor
})
Sujit
  • 610
  • 7
  • 26
  • 1
    Why change it to the layer? – rmaddy Sep 13 '16 at 05:35
  • I am not found animation for View background color. Yes of course we can use like - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ((RouteListCell *)cell).name.backgroundColor = [UIColor clearColor]; [((RouteListCell *)cell).name backgroundGlowAnimationFromColor:[UIColor whiteColor] toColor:[UIColor redColor] clearAnimationsFirst:YES]; } – Sujit Sep 13 '16 at 05:49
  • 1
    @AVEbrahimi I found this answer from http://stackoverflow.com/questions/3762561/how-to-animate-the-background-color-of-a-uilabel – Sujit Sep 13 '16 at 06:12
  • @Sujit In the future, when you copy some one else's answer, you should include the proper reference in your answer. Otherwise it is plagiarism. Better yet, if you think another question is a duplicate, vote to close the question as a duplicate. – rmaddy Sep 13 '16 at 16:04
  • @rmaddy Thanks buddy. I will remember – Sujit Sep 14 '16 at 04:09