UIImageView in UITableViewCell is not animated when animated UIImage is assigned twice

I am trying to display an animated UIImage in a UITableViewCell imageView. The animation image is displayed after the first assignment, but not with each subsequent attempt.

Here is the code for the TableViewController:

#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImage *animatedImage; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.animatedImage = [UIImage animatedImageNamed:@"syncing" duration:1.0]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static BOOL second = NO; static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (second) { cell.imageView.image = nil; NSLog(@"Removed image"); } else { cell.imageView.image = self.animatedImage; NSLog(@"Added image"); if (![cell.imageView isAnimating]) { [cell.imageView startAnimating]; NSLog(@"Started animation for UIImageView: %@", cell.imageView); } } second = !second; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; } @end 

And this is the result when I double click on the cell:

 Added image Started animation for UIImageView: <UIImageView: 0x7197540; frame = (0 0; 0 0); opaque = NO; userInteractionEnabled = NO; animations = { UIImageAnimation=<CAKeyframeAnimation: 0x715bc80>; }; layer = <CALayer: 0x71975a0>> - (null) Removed image Added image Started animation for UIImageView: <UIImageView: 0x7197540; frame = (6 6; 30 30); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x71975a0>> - (null) 
+4
source share
1 answer

I strongly recommend that you do not do animations for images in cellForRowAtIndexPath , because if you have more images, an unwanted effect will appear when you scroll quickly (cell images will switch due to the convenience of using cells).

What I did in one of my projects, I applied the method – scrollViewDidScroll: for UITableViewDelegate (which corresponds to UIScrollViewDelegate), and there I called a method that will animate images only on visible cells (tableView.visibleCells).

On the other hand, I do not understand why you use static BOOL second = NO; , you can just check if cell.imageView.image == is zero or not.

Also check the animation code, it is possible that something is not working there (remember that the cells are reused).

+1
source

Source: https://habr.com/ru/post/1480334/


All Articles