質問

In my Application, I have a NSMutableArray with UIImage in it.

I would like to display the first UIImage in the array for three seconds, and then to display the second image.

All of this should happen when I press a UIButton.

Below is my code:

[testImageView setImage:[arr objectAtIndex:0]] ;
sleep(3) ;
[testImageView setImage:[arr objectAtIndex:1]] ;

testImageView is a UIImageView object on my screen.

When I'm running this code, my button remain pressed for three seconds and only the second image is displayed.

What should I do?

役に立ちましたか?

解決

Try using one of the most obscure methods of UIImageView.

UIImageView *myImageView = [[UIImageView alloc] initWithFrame:...];

myImageView.animationImages   = images;
myImageView.animationDuration = 3.0 * images.count;

[self.view addSubview:myImageView];

Then, when you wanna start animating

[myImageView startAnimating];

I don't know what you plan on doing with this, but 3 seconds might be too much. If you're doing some sort of presentation-ish, then this method might not be very good, since there's no easy way of going back.

他のヒント

The reason that your button remains pressed is because you slept main thread for 3 seconds, this means that nothing is going to happen to your application (at least the user interface) until thread is back to active.

There are multiple ways to achieve what you wish, but you must put a timer on the background thread. I would suggest you put the code to set the second image in another method first and make array into a property.

- (void)setImage
{
    [testImageView setImage:self.yourArray[1]];
}

Then you can use one of the following ways to execute the method:

  1. Use a NSTimer:

    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(setImage) userInfo:nil repeats:NO]
    
  2. Use performSelector method of NSObject:

    [self performSelector:@selector(setImage) withObject:nil afterDelay:3.0];
    
  3. Use Grand Central Dispatch.

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0), dispatch_get_main_queue(), ^{
        [self setImage];
    });
    

Any of the ways described above will work.

Read more information about concurrency on the links below:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top