使用时间延迟更改UITextField文本

时间:2013-08-27 13:37:21

标签: ios

我试图以这种方式每1.5秒更换一次UItextFieeld:

-(void)Welcome{

UITextField* WelcomeField = [[UITextField alloc] initWithFrame:CGRectMake(50,230,220,80)];
[self.view addSubview:WelcomeField];
WelcomeField.placeholder = @"Welcome";
WelcomeField.font = [UIFont fontWithName:@"Chalkduster" size:40];
[WelcomeField setBackgroundColor:[UIColor clearColor]];

NSTimer* TimeCounterWelcome = [NSTimer scheduledTimerWithTimeInterval: 1.5 target: self
                                                         selector: @selector(ChangeLanguage:) userInfo: nil repeats: YES];
}

- (IBAction)ChangeLanguage:(id)sender{

WelcomeField.placeholder = @"Goodby";


NSTimer* TimeCounterWelcome = [NSTimer scheduledTimerWithTimeInterval: 1.5 target: self
                                                         selector: @selector(ChangeLanguage2:) userInfo: nil repeats: YES];

}

- (IBAction)ChangeLanguage2:(id)sender{

WelcomeField.placeholder = @"Friend";

}

问题是我有30个单词,而且我不能重复30次代码。有更快的方法吗?

3 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

-(void)Welcome{

UITextField* WelcomeField = [[UITextField alloc]initWithFrame:CGRectMake(50,230,220,80)];
[self.view addSubview:WelcomeField];
WelcomeField.placeholder = @"Welcome";
WelcomeField.font = [UIFont fontWithName:@"Chalkduster" size:40];
[WelcomeField setBackgroundColor:[UIColor clearColor]];

// global integer 'wordIndex'
wordIndex = 0;

// global NSArray 'allTheWords'
allTheWords = [NSArray arrayWithObjects:word1, word2, word3, etc., nil];

NSTimer* TimeCounterWelcome = [NSTimer scheduledTimerWithTimeInterval: 1.5 target: self
                                                     selector: @selector(ChangeLanguage:) userInfo: nil repeats: YES];
}

-(void)ChangeLanguage:(id)sender{
    NSString * nextWord = [allTheWords objectAtIndex:wordIndex];
    WelcomeField.placeholder = nextWord;
    wordIndex++;

    // assuming to start from beginnning again
    if(wordIndex >= 30) {
        wordIndex = 0;
    }
}

一个小样式评论:尝试使用小写字母i.s.o开始方法和变量名称。大写字母。如果您想要遵循Objective-C编码指南,那就更好了。

答案 1 :(得分:0)

是的,有更好的方法可以做到。

定义一个包含所有30个单词的数组。在循环数组时,设置占位符并设置延迟。

答案 2 :(得分:0)

声明一个NSArray,它保存所有30个值并每隔1.5秒循环一次,直到达到最后一个项目。

for (id object in array) {
    // do something with object
}