Question

I have a routine that draws a gearwheel using CoreGraphics and drawRect. I used a button to advanced the gears through the stages:

-(IBAction)advanceButtonPressed:(id)sender{

stage=stage+1;

if (stage==4) stage=0;

[self setNeedsDisplay];

}

The routine for drawing the gear is in drawRect, and the gear teeth are drawn in a new position depending on the vale of stage, which is passed to drawRect. In four steps, one per button press, the gear turns to its new position (one segment around the circle.)

I changed the buttonPressed routine to have it do the four stages in a loop, so I only need to press the button once, but it doesn't work:

-(IBAction)buttonPressed:(id)sender{

for (stage=0;stage<4;stage++){

    NSLog(@"%i",stage);

[self setNeedsDisplay];
}

}

My NSLog shows that stage goes through its four values, just as it would in the earlier routine. But setNeedsDisplay is only executed once, (as a NSLog trace in drawRect confirms) so the gear is displayed in its final position but not the intermediate stages. It looks like setNeedsDisplay only executes when the button routine finishes, despite it being inside the loop.

Is there any way to force it to execute?

Was it helpful?

Solution

The iPhone only updates the screen 60 times a second no matter how often you call setNeedsDisplay. Your loop is going to execute in less than 1/60th of a second. That's why you only will see the last state.

If you want to show all four states through one button press then you could use a timer or performSelector: afterDelay to show all four states. A little more complicated but there you go.

OTHER TIPS

Invoking setNeedsDisplay just marks the view to be redrawn at the next drawing cycle.

To redraw it during your method, you could explicitly call drawRect:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top