问题描述
我正在为 iPhone 开发一个应用程序.我的问题是如何每 0.5 秒显示一个带有不同文本的新标签.例如,它将显示蓝色、红色、绿色、橙色和紫色;一个接一个.现在我正在这样做:
I am developing an application for the iPhone. The question I have is how to display a new label with a different text every .5 seconds. For example, it would display Blue, Red, Green, Orange and Purple; one right after one another. Right now I am doing this:
results = aDictionary;
NSArray *myKeys = [results allKeys];
NSArray *sortedKeys = [myKey sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
int keyCount = [sortedKeys count];
while (flag == NO) {
NSTimeInterval timeMS = [startDate timeIntervalSinceNow] * -10000.0;
if (timeMS >= i) {
ii++;
i += 1000;
NSLog(@"endDate = %f", timeMS);
int randomNumber = rand() % keyCount + 1;
lblResult.text = [results valueForKey:[sortedKeys objectAtIndex:(randomNumber - 1)]];
result = [results valueForKey:[sortedKeys objectAtIndex:(randomNumber - 1)]];
lblResult.text = result;
}
if (ii > 25) {
flag = YES;
}
}
lblResult.text = [results valueForKey:[sortedKeys objectAtIndex:(sortedKeys.count - 1)]];
这个函数在 viewDidAppear 函数中被调用并且当前没有显示新的标签.它只显示最后一个.我做错什么了吗?解决这个问题的最佳方法是什么?
this function is called at the viewDidAppear Function and currently isn't displaying the new labels. It only displays the one at the end. Am I doing anything wrong? What would be the best method to approach this?
推荐答案
问题是你没有给运行循环一个运行的机会(因此,绘制发生).您需要使用一个 NSTimer
定期触发并设置下一个文本(您可以记住当前所在的实例变量).
The problem is that you're not giving the run loop a chance to run (and therefore, drawing to happen). You'll want to use an NSTimer
that fires periodically and sets the next text (you could remember in an instance variable where you currently are).
或者使用类似的东西(假设 items 是一个 NSArray
保存你的字符串):
Or use something like this (assuming that items is an NSArray
holding your strings):
- (void)updateText:(NSNumber *)num
{
NSUInteger index = [num unsignedInteger];
[label setText:[items objectAtIndex:index]];
index++;
// to loop, add
// if (index == [items count]) { index = 0; }
if (index < [items count]) {
[self performSelector:@selector(updateText:) withObject:[NSNumber numberWithUnsignedInteger:index] afterDelay:0.5];
}
}
在开始时(例如在 viewDidAppear:
中),然后您可以调用
At the beginning (e.g. in viewDidAppear:
), you could then call
[self updateText:[NSNumber numberWithUnsignedInteger:0]];
触发初始更新.
您当然需要确保当您的视图消失时执行不会继续,您可以通过取消 performSelector 来做到这一点,或者如果您正在使用计时器,只需将其无效或使用布尔值,或...
You'd of course need to ensure that the performs are not continuing when your view disappears, you could do this by canceling the performSelector, or if you're using a timer, by simply invalidating it, or using a boolean, or ...
如果你想变得更漂亮,请使用 GCD :)
And if you want to get really fancy, use GCD :)
这篇关于使用 iPhone 应用程序不能立即显示标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!