我已经编写了程序,它从数组中选择一个随机元素。
一旦我按下"Start“按钮,我如何循环该代码?
我希望,一旦按下“开始”按钮,就会从数组中选择一个新元素,并每隔5秒将其写入文本字段中。谢谢你的回答。
@implementation MARandom
- (IBAction)Start:(id)sender {
NSArray *tones;
tones = [NSArray arrayWithObjects: @"F#0", @"Gb0", @"G0", @"G#0",@"Ab0",@"A0",@"A#0",@"Bb0",@"B0",
@"C1",@"C#1",@"Db1",@"D1",@"D#1",@"Eb1",@"E1",@"F1",@"F#1",@"Gb1",@"G1",@"G#1",@"Ab1",@"A1",@"A#1",@"Bb1",@"B1",
@"C2",@"C#2",@"Db2",@"D2",@"D#2",@"Eb2",@"E2",@"F2",@"F#2",@"Gb2",@"G2",@"G#2",@"Ab2",@"A2",@"A#2",@"Bb2",@"B2",
@"C3",@"C#3",@"Db3",@"D3",@"D#3",@"Eb3",nil];
i= (arc4random() % 48);
NSString *Tone;
Tone = [tones objectAtIndex: i];
[TextField setStringValue:(NSString *)Tone];
}
发布于 2011-09-20 03:53:50
请尝试以下操作:
- (IBAction)Start:(id)sender {
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(updateTextFieldWithRandomNumber)
userInfo:nil
repeats:YES];
}
-(void)updateTextFieldWithRandomNumber{
NSArray *tones;
tones = [NSArray arrayWithObjects: @"F#0", @"Gb0", @"G0", @"G#0",@"Ab0",@"A0",@"A#0",@"Bb0",@"B0",
@"C1",@"C#1",@"Db1",@"D1",@"D#1",@"Eb1",@"E1",@"F1",@"F#1",@"Gb1",@"G1",@"G#1",@"Ab1",@"A1",@"A#1",@"Bb1",@"B1",
@"C2",@"C#2",@"Db2",@"D2",@"D#2",@"Eb2",@"E2",@"F2",@"F#2",@"Gb2",@"G2",@"G#2",@"Ab2",@"A2",@"A#2",@"Bb2",@"B2",
@"C3",@"C#3",@"Db3",@"D3",@"D#3",@"Eb3",nil];
i= (arc4random() % 48);
NSString *Tone;
Tone = [tones objectAtIndex: i];
[TextField setStringValue:(NSString *)Tone];
}
还要考虑在一个地方准备数组,而不是重复调用的代码,可能是在viewDidLoad。
注意:未测试的代码,但应该可以工作。
https://stackoverflow.com/questions/7475778
复制相似问题