【问题标题】:Display random pictures with timer delay显示带有定时器延迟的随机图片
【发布时间】:2014-01-01 21:17:08
【问题描述】:

我正在制作一个应用程序,它从预设的图片组中随机选择一张图片并将其显示到图像视图中。这应该每隔一秒左右发生一次,直到它经历了 20 个周期。

听到的是我的头文件和实现代码:

@interface spinController : UIViewController
{
IBOutlet UIImageView *imageHolder;
NSTimer *MovementTimer;    
}
-(IBAction)Button:(id)sender;
-(void)displayPic;
@end


@implementation spinController
-(IBAction)Button:(id)sender
{
int count = 0;
while (count <20)
{
   [NSTimer scheduledTimerWithTimeInterval:1 target:self    selector:@selector(displayPic) userInfo:nil repeats:NO];
    count++;
}
}
-(void)displayPic
{
int r = arc4random() % 2;
if(r==0)
{
imageHolder.image = [UIImage imageNamed:@"puppy1.jpg"];
}
else
{
imageHolder.image = [UIImage imageNamed:@"puppy2.jpg"];
}
}   
-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}  
@end

我在 WPF 中以更高级的形式制作了此应用程序,但遇到了图片无法正确循环的类似问题。如果我点击旋转,它会随机化,但不会经历 20 个周期……只有一个。这是我在objective-c 中的第一个应用程序,并意识到我选择的方法的效率将决定我的应用程序以更复杂的形式运行的好坏。任何帮助将不胜感激。

【问题讨论】:

标签: ios iphone objective-c xcode5


【解决方案1】:

问题是您在 while 循环中重复调用计时器;并且由于该特定的 while 循环将在大约一毫秒内完成,因此您将立即连续创建 20 个计时器。因此,imageHolder 视图中只会显示最终图像。编辑:即使循环每次迭代花费的时间超过一毫秒,我相信 NSTimer 在方法退出之前不会真正触发。

为了像您尝试那样一个接一个地显示图像,(1) 使用 NSTimer 而不使用 while 循环,(2) 使用 count 类跟踪迭代 实例变量,以免在各种方法完成后丢失变量的值,以及 (3) 将 NSTimer 传递给 displayPic 方法,这样您就可以从那里使计时器失效第 20 次迭代。例如:

// Declare the "count" instance variable.
int count;

-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
} 

-(IBAction)Button:(id)sender {
    // The count starts at 0, so initialize "count" to 0.
    count = 0;

    // Use an NSTimer to call displayPic: repeatedly every 1 second ("repeats" is set to "YES")
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(displayPic:) userInfo:nil repeats:YES];
}

// Pass along the NSTimer to the displayPic method so that it can be invalidated within this method upon the 20th iteration
-(void)displayPic:(NSTimer *)timer {

    // Get the random number
    int r = arc4random() % 2;

    // If the number is 0, display puppy1.jpg, else display puppy2.jpg.
    if(r == 0) {
        imageHolder.image = [UIImage imageNamed:@"puppy1.jpg"];
    }
    else {
        imageHolder.image = [UIImage imageNamed:@"puppy2.jpg"];
    }

    // Increment "count" to reflect the number of times the NSTimer has called this method since the button press
    count ++;

    // If the count == 20, stop the timer.
    if (count == 20)
        [timer invalidate];
}   

@end

【讨论】:

  • 这很有意义。我的印象是暂停会暂停主线程。这也解决了我在 display pic 方法中使用 count 实例变量时遇到的另一个问题。
【解决方案2】:

更改重复为YES。这会导致计时器一次又一次地运行。然后代替 while 循环检查方法本身的计数。

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多