在目标c中,Xcode按下按钮即可更改UI图像



当我按下按钮时,我希望第一个图像显示在UIImageView中,停留一小段时间,然后显示下一个图像。一段时间后,仅显示第二个图像。第一个图像永远不会出现。

//  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

U可以尝试放置

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

而不是

[NSThread sleepForTimeInterval:2];

称之为

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

这里的问题是,在操作系统有机会绘制之前,您要替换图像。由于所有这三个操作(更改图像、等待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

然后:

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

如果您希望颜色交替,您可以在创建代码中为repeats:value传递YES,然后将-updateColor:更改为交替。。。或者移动到下一个颜色。

最新更新