0

我正在尝试以这种方式每 1.5 秒更改一次 UItextField 上的文字:

-(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次。有更快的方法吗?

4

3 回答 3

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;
    }
}

一点风格评论:尝试以小写字母和大写字母开头的方法和变量名。如果您想遵循 Objective-C 编码指南,那就更好了。

于 2013-08-27T14:30:36.070 回答
0

是的,有更好的方法来做到这一点。

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

于 2013-08-27T13:42:52.577 回答
0

声明一个包含所有 30 个值的 NSArray,并每隔 1.5 秒循环一次,直到到达最后一项。

for (id object in array) {
    // do something with object
}
于 2013-08-27T13:44:15.133 回答