Search code examples
iosobjective-ccocoa-touchuikitcore-animation

How to use DrawRect correctly


Im currently building Custom UIActivityIndicator. In order to do that I created the following draw rect function:

-(void) drawRect:(CGRect)rect  
{
CGPoint point;
NSLog(@"here %d",stage);`

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 2.0);

for (int i = 1 ; i<=10; ++i) {


    CGContextSetStrokeColorWithColor(ctx, [[self getColorForStage:stage+i WithAlpha:0.1 *i] CGColor]);
    point = [self pointOnOuterCirecleWithAngel:stage+i];
    CGContextMoveToPoint(ctx, point.x, point.y);
    point = [self pointOnInnerCirecleWithAngel:stage+i];
    CGContextAddLineToPoint( ctx, point.x, point.y);
    CGContextStrokePath(ctx);
}



stage++;
}

And i added an NSTimer to call [self setNeedsDisplay];

The animation works fine BUT when I import it to my application every time i will scroll a table or do anything the animation will stop until the table stops moving.

I assume that only after the UI finish to update it update my DrawRect but how can I work around it OR do it the right way


Solution

  • You have to schedule your timer manually with a different runloop mode, if you want it to fire while a table view (or any other scroll view) is scrolling. By default, timers don't fire while scrolling to improve performance.

    NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(setNeedsDisplay) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    

    (you'd get the default behavior with NSDefaultRunLoopMode instead of NSRunLoopCommonModes.)