I have a UITableView loading its data from the Web, and while the data is loading there are few cells, to indicate the process. Each cell got an UIImageView inside which i want to be spinning constantly.
Inside the UITableViewController i got this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
//there are three "default" cells
return self.datasource.count > 0 ? self.datasource.count : 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.datasource.count)
{
//return a cell with loaded data
}
else
{
LoadingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LoadingIndicationCell"];
return cell;
}
}
LoadingTableViewCell has a *.xib file with a corresponding reference outlet to the UIImageView, called "circle"
- (void)awakeFromNib {
self.circle.alpha = .3f;
self.spinning = NO;
[self startSpin];
}
- (void) spinWithOptions: (UIViewAnimationOptions) options {
NSLog(@"SPINNIN'");
// this spin completes 360 degrees every 2 seconds
[UIView animateWithDuration: 0.5f
delay: 0.0f
options: options
animations: ^{
_circle.transform = CGAffineTransformRotate(_circle.transform, M_PI / 2);
}
completion: ^(BOOL finished) {
if (finished) {
if (_spinning) {
[self spinWithOptions: UIViewAnimationOptionCurveLinear];
} else if (options != UIViewAnimationOptionCurveEaseOut) {
[self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
}
}
}];
}
- (void) startSpin {
if (!self.spinning) {
self.spinning = YES;
[self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
}
}
- (void) stopSpin {
self.spinning = NO;
}
It seems to spin 2 times and then stops. In the console there are 6 "SPINNIN'" outputs, two for each cell, i suppose.
I'm very new to iOS-development, been tryin' to figure this out the entire evening. Btw, what will happen to these cell objects when they will get replaced by cells with loaded data? Where do i call stopSpin then?
Eventually i ended up with this code:
- (void) spinWithOptions: (UIViewAnimationOptions) options {
if([self isHidden]) [self stopSpin]; //stop spinning when the cell got replaced
// this spin completes 360 degrees every 2 seconds
[UIView animateWithDuration: 1.0f
delay: 0.0f
options: options
animations: ^{
_circle.transform = CGAffineTransformRotate(_circle.transform, M_PI / 2);
}
completion: ^(BOOL finished) {
if (_spinning) {
[self spinWithOptions: UIViewAnimationOptionCurveLinear];
}
}];
}