简体   繁体   中英

Change UIImage from UIButton after x seconds in iOS

I I'm trying change the uiimage from a uibutton after 1 seconds. I tried sleep the thread with

[button1 setImage:[UIImage imageNamed:@"sameThing.png"] forState:UIControlStateNormal];

[NSThread sleepForTimeInterval:1]; 

[button1 setImage:[UIImage imageNamed:@"interrogation.png"] forState:UIControlStateNormal];

but the image is not changed and the Thread is executed normally Thanks for your suggestions

Try this

[self performSelector:@selector(updateBtnImage:)
           withObject: someObject       
           afterDelay:1];



-(void) updateBtnImage: (id) obj
{    
         //Set image here
         //If still not updating image here dispatch block on main thread manually like this 
            dispatch_async(dispatch_get_main_queue(), 
             ^{
             //Set image in this block 
              });

}

This is not how you do these kind of things on iOS. First of all, making the main thread sleep is a bad idea. You would block (freeze) the user interface of your app for one second. Instead you have to schedule the second method call to be executed later.

You could define a new method:

- (void)updateButtonWithImageNamed:(NSString *)imageName {
    [button1 setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}

and then schedule it like this:

[self performSelector:@selector(updateButtonWithImageNamed:) 
           withObject:@“interrogation.png"
           afterDelay:1.0f];

As an alternative to performSelector:WithObject:afterDelay , you could use GDC's dispatch_after :

[button1 setImage:[UIImage imageNamed:@"sameThing.png"] forState:UIControlStateNormal];

double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [button1 setImage:[UIImage imageNamed:@"interrogation.png"] forState:UIControlStateNormal];
});

There's a snippet already defined in Xcode to do this when you type dispatch_after . The upside is that you don't have to define a new method. The downside is that you must be careful with retain circles in your blocks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM