Carl
Carl

Reputation: 209

iPhone: drawRect called once

I'm calling setNeedsDisplayInRect from an NSTimer function every two seconds. This works perfectly, and draws a square in a random position, with a random color. However, in some circumstances I would like to draw a square x number of times in the NSTimer function (using a for loop) - but, after numerous error testing it seems that drawRect is only called once even though I am running setNeedsDisplayInRect x number of times? I would love some help as I've been trying to figure out this problem all day long. Carl.

Edit below is my code...

View

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
    CGContextSetFillColorWithColor(context, currentColor.CGColor);
    CGContextAddRect(context, redrawRect);
    CGContextDrawPath(context, kCGPathFillStroke);
}

-(void)drawInitializer 
{
    int x = (int)arc4random() % [self.xCoordinates count]; 
    int y = (int)arc4random() % [self.yCoordinates count]; 
    self.currentColor = [UIColor randomColor];
    self.redrawRect = CGRectMake ([[self.xCoordinates objectAtIndex:x] intValue],       [[self.yCoordinates objectAtIndex:y] intValue], 25, 25);
    [self setNeedsDisplayInRect:redrawRect];
}

Controller

- (void) handleTimer: (NSTimer *) timer
{
    for(int i=0; i<5; i++) 
    {
         [self.squareView drawInitializer];
    }
}

Upvotes: 2

Views: 2574

Answers (2)

D.C.
D.C.

Reputation: 15588

you could create a class that has the ability to draw itself, then create as many instances of this class that you need.

Upvotes: 0

Thomas Zoechling
Thomas Zoechling

Reputation: 34263

You could refactor the code so that you have a simple class that:

  • stores color
  • stores position
  • has a method to generate random positions, colors, ...

You could then create as many instances as you want and push them into a NSMutableArray.
This way you can iterate over that list, and draw each object in your draw routine.
Whenever you add/delete/modify one of your objects, call setNeedsDisplay:

Upvotes: 1

Related Questions