2014-10-22 3 views
0

У меня есть UITableView, что внутри его UITableViewCells я анимирую слой круговой диаграммы с CABasicAnimation.Прокрутка UITableView с CABasicAnimation в uitableviewcell делает анимацию нервной

Дело в том, что если я прокручиваю представление таблицы во время его анимации слоя - анимация слоя стала нервной, а не «чистой».

Анимация слоя начинается в:

tableView:willDisplayCell:forRowAtIndexPath: 

Использование dequeueReusableCellWithIdentifier, а также:

static NSString *cellIdentifier = @"CellIdentifier"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
if(!cell) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    ... 
} 
... 
return cell; 

таймера расписания для обновления прогресса диаграммы:

- (void)startAnimation 
{ 
self.elapsedTimeTimer = nil; 
self.elapsedTimeTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 
                  target:self 
                  selector:@selector(updateProgress) 
                  userInfo:nil 
                  repeats:YES]; 
[[NSRunLoop currentRunLoop] addTimer:self.elapsedTimeTimer 
          forMode:NSRunLoopCommonModes]; 
} 

- (void)updateProgress 
{ 
    if(!self.didEndProgress) 
     self.progress += 0.01; 

    if(self.progress >= self.finalPercents/100) 
    { 
     [self.elapsedTimeTimer invalidate]; 
     self.elapsedTimeTimer = nil; 
    } 
} 

реализации слоя:

@implementation CircleGraphLayer 
@dynamic progress; 

+ (BOOL)needsDisplayForKey:(NSString *)key { 
return [key isEqualToString:@"progress"] || [super needsDisplayForKey:key]; 
} 

- (id<CAAction>)actionForKey:(NSString *)aKey { 
if ([aKey isEqualToString:@"progress"]) { 

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:aKey]; 
    animation.fromValue = [self.presentationLayer valueForKey:aKey]; 
    return animation; 
} 
return [super actionForKey:aKey]; 
} 

- (void)drawInContext:(CGContextRef)context { 

CGRect circleRect = CGRectInset(self.bounds, 1, 1); 
CGContextClearRect(context, circleRect); 

CGColorRef borderColor = [[UIColor colorWithWhite:1.0 alpha:0.4] CGColor]; 
CGColorRef backgroundColor = [[UIColor clearColor] CGColor]; //[[UIColor colorWithWhite: 1.0 alpha: 0.15] CGColor]; 

CGContextSetFillColorWithColor(context, backgroundColor); 
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); 
CGContextSetLineWidth(context, 1.0f); 

CGContextFillEllipseInRect(context, circleRect); 
CGContextStrokeEllipseInRect(context, circleRect); 

CGFloat radius = MIN(CGRectGetMidX(circleRect), CGRectGetMidY(circleRect)); 
CGPoint center = CGPointMake(radius, CGRectGetMidY(circleRect)); 
CGFloat startAngle = -M_PI/2; 
CGFloat endAngle = self.progress * 2 * M_PI + startAngle; 
CGContextSetFillColorWithColor(context, borderColor); 
CGContextMoveToPoint(context, center.x, center.y); 
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); 
CGContextClosePath(context); 
CGContextFillPath(context); 
[super drawInContext:context]; 
} 
@end 

Любая полезная помощь будет оценена по достоинству.

+0

Что вам говорят инструменты? –

+0

Какой шаблон следует выбрать для запуска в Инструментах? Core Animation? – PizzaByte

ответ

0

Я не могу оставить комментарий из-за моей репутации. Это не ответ на главную проблему, а решение для небольшой ошибки в коде: если вы используете [NSTimer scheduledTimerWithTimeInterval:...] вместо [NSTimer timerWithTimeInterval:...], вам не нужно добавлять таймер в [NSRunLoop currentRunLoop]. См. «Таймеры планирования в циклах запуска» в разделе NSTimer Class Reference. Надеюсь, это поможет.

+0

На самом деле вы можете видеть, что OP добавляет таймер к 'NSRunLoopCommonModes'. Когда вы используете 'schedTimer ...', он добавляется в 'NSDefaultRunLoopMode', поэтому два не будут _do_ одинаковыми. –

Смежные вопросы