我正在创建一个应用程序,当用户按下按钮时,在UILabel中显示一个随机单词(NSDictionary中的一个键)和另一个UILabel中的相关单词列表(NSArray,即显示键的值)。例如:如果用户按下按钮,主要单词可能是“Cat”,列表可能是“lion”,“snow leopard”,“tiger”。
我想循环文本输出,以便用户按下按钮一次,得到一个单词和一个列表,有一个定时暂停,然后单词和列表刷新。这是我到目前为止的方法:
- (IBAction)changeWord:(UIButton*)sender {
//next line displays the randomly selected NSDictionary key, such as "Cat" in a label
self.label.text = [self.dictionary selectKey];
//next two lines displays the value associated with the selected key (an array), such as "lion", "snow leopard", "tiger" in another label
NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
self.listLabel.text = labelText;
}
这显然不会循环,只需按下按钮就会显示两个标签的新输出。我认为创建一个循环,循环次数与字典键一样多,可以解决问题的一半:
- (IBAction)changeWord:(UIButton*)sender {
//next line counts the keys in the NSDictionary
NSInteger numberOfKeys = [self.dictionary CountKeys];
for( int index = 0; index < numberOfKeys; index++ )
{
self.label.text = [self.dictionary selectKey];
NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
self.listLabel.text = labelText;
//need some type of timer here!
}
但我需要某种类型的计时器,它会在刷新之前定期暂停显示。那就是我被困住的地方!
有没有人有任何指示?
非常感谢!
答案 0 :(得分:2)
您可以使用NSObject的方法performSelector:withObject:afterDelay\]
:
- (IBAction)changeWord:(UIButton*)sender
{
[self changeWord];
}
- (void)changeWord
{
if (musicStopped) return;
//next line displays the randomly selected NSDictionary key, such as "Cat" in a label
self.label.text = [self.dictionary selectKey];
//next two lines displays the value associated with the selected key (an array), such as "lion", "snow leopard", "tiger" in another label
NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
self.listLabel.text = labelText;
// Add this line
[self performSelector:@selector(changeWord) withObject:nil afterDelay:30.0];
}