drw
drw

Reputation: 943

can not get setNeedsDisplay to work within a loop for UIImageView

A frequently answered question, I'm afraid but I am pretty much in the dark on this.

Within my view controller I have the following method to switch back and forward between two images a total of 5 times

- (IBAction)cycle{

 BOOL select1;
 select1=YES;

 UIImage *image1 = [UIImage imageNamed:@"image1.png"];
 UIImage *image2 = [UIImage imageNamed:@"image2.png"];

 for (int i=0; i<5; i++) {

  if (select1){
   [imageview setImage:image1];
  } else {
   [imageview setImage:image2];
  }

  [NSThread sleepForTimeInterval:1.0];

  [imageview setNeedsDisplay];

 }
}

The problem is that the setNeedsDisplay message does not work within the loop and the view is only updated when the method quits.

Is there any thing I can do here? Is the approach feasible or am I completely down the wrong track. This is very much a test program (I am new to this language) but it would be useful to control something like this programmatically. The next step app will implement randomly changing times between picture changes.

Can anyone help me on this?

Upvotes: 0

Views: 912

Answers (1)

No one in particular
No one in particular

Reputation: 2672

Wrong track. Calling

[NSThread sleepForTimeInterval:1.0];

Is only trying to put the main thread asleep. The problem is that this is the thread that's actually does the drawing. You need to end what you're doing and give control bakc to the NS runtime so that it can update gui elements.

Try using NSTimer to create a scheduled timer. Have it repeat with the time interval that you want. All that you then have to do is set the image:

if (select1){     
   [imageview setImage:image1];     
  } else {     
   [imageview setImage:image2];     
  } 

there's no need for

[imageview setNeedsDisplay];

As the imageview will handle that for itself.

Upvotes: 1

Related Questions