Reputation: 468
I'm trying to animate my label in my UICollectionViewCell. I want to go randomly through the array and set the label randomly 10 times and then it stops at a random string from my array.
The problem is, it goes through my array (debugged it with a simple NSLog) BUT the label setText isn't used till the last number of my loop and the label is then set.
Here is my code:
-(void)animate{
long index;
for(detail* cells in [[self col] visibleCells]){
NSIndexPath *indexPath = [[self col] indexPathForCell:cells];
if ([array count] >= 3) {
index = 2 * indexPath.section + indexPath.row;
}else{
index = 1 * indexPath.section + indexPath.row;
}
for (int i = 0; i <= 10; i++) {
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
[NSThread sleepForTimeInterval:0.10];
NSLog(@"%i", i);
}
}
}
And here is my returnRandomOptie
from my custom Cell class:
-(NSString *) returnRandomOptie {
NSUInteger randomIndex;
NSString *string;
if ([opties count] != 0) {
randomIndex = arc4random() % [opties count];
string = [NSString stringWithFormat:@"%@", [opties objectAtIndex:randomIndex]];
}
return string;
}
So basically I want that the for loop in my animate method, always sets the text in my label. And now it doesn't do that. Just at the last loop.
What am I doing wrong?
Kind Regards!
Upvotes: 0
Views: 945
Reputation: 9154
You have to perform the sleep async and update the label in the main thread, try this instead :
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i <= 10; i++) {
dispatch_async(dispatch_get_main_queue(), ^{
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
});
[NSThread sleepForTimeInterval:0.10];
NSLog(@"%i", i);
}
});
Upvotes: 4
Reputation: 5182
Try this,
-(void)animate{
....
for (int i = 0; i <= 10; i++) {
dispatch_async(dispatch_get_main_queue(), ^{
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
});
[NSThread sleepForTimeInterval:0.10];
NSLog(@"%i", i);
}
...
}
Upvotes: 0