2012-03-09 55 views
0

当我按下按钮我想所述第一图像以在显示的UIImageView,停留很短的时间周期,然后将下一个图像来显示。经过一段时间后才会显示第二张图片。第一个图像永远不会出现。在以按下按钮目标C的Xcode更改UIImages

// TestProjectViewController.m 
// Created by Jack Handy on 3/8/12. 

#import "TestProjectViewController.h" 

@implementation TestProjectViewController 

@synthesize View1= _view1; 
@synthesize yellowColor = _yellowColor; 
@synthesize greenColor = _greenColor; 


    - (IBAction)button:(id)sender { 

     _greenColor = [UIImage imageNamed: @"green.png"]; 
      _view1.image = _greenColor; 

    [NSThread sleepForTimeInterval:2]; 

     _yellowColor = [UIImage imageNamed: @"yellow.png"]; 
      _view1.image = _yellowColor; 

} 
@end 
+0

杰克,很高兴地听到,摸索出。如果你发现任何有用的答案,请投票。如果其中一个是您的解决方案,请将其标记为答案。 – gaige 2012-03-09 10:41:02

回答

0

U可以试着放置

_yellowColor = [UIImage imageNamed: @"yellow.png"]; 
      _view1.image = _yellowColor; 

代替作为

[NSThread sleepForTimeInterval:2]; 

调用这个

[self performSelector:@selector(changeColor) withObject:nil afterDelay:2]; 
+0

我试过这个,得到这个错误 – 2012-03-09 01:21:57

+0

我得到了什么错误? – 2012-03-09 01:24:11

+0

1,他没有实施'changeColor' – JiaYow 2012-03-09 01:24:52

0

在这里的问题是,要更换的操作系统有机会绘制之前的图像。由于所有这三种操作:更改图像,等待2秒,再次更改图像)发生在按钮操作返回之前,您正在阻止主线程执行并因此刷新屏幕。所以,发生的事情是,在2秒后,屏幕上会显示最近放置的图像。

你必须等待单独发生。有三种典型的方式做到这一点,每一个都有自己的优点: - 送自己使用-performSelector:withObject:afterDelay: 延迟的消息 - 产卵另一个线程或使用调度队列在后台为睡眠运行一个线程,然后发送邮件从 到主线程 - 或者,使用一个计时器。

我的建议是使用定时器,因为它很容易取消,如果你需要做一些像移动到另一个屏幕。

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target: self selector: @selector(updateColor:) userInfo: nil repeats: NO]; 
// store the timer somewhere, so that you can cancel it with 
// [timer invalidate]; 
// later as necessary 

再后来:在创建码值,然后改变-updateColor:交替...或招:

-(void)updateColor:(NSTimer*)timer 
{ 
    _yellowColor = [UIImage imageNamed: @"yellow.png"]; 
    _view1.image = _yellowColor; 
} 

如果你想要的颜色交替,你可以通过YES的重复到下一个颜色。

+0

得到它的工作谢谢! – 2012-03-09 01:53:56