我正在尝试创建一个数组,该数组包含x个文字字符串,在您点击UIButton后会随机将其发送到UILabel。
我应该如何构建.h和.m文件来执行此操作?另外,生成我需要的随机数的最佳方法是什么?
答案 0 :(得分:1)
您将获得索引的随机整数,然后将您获得的对象传递给UILabel的文本属性,例如:
//assuming you already have an NSArray of strings
myLabel.text = [arrayOfString objectAtIndex:arc4random() % [arrayOfString count]];
您将上面的代码放在按钮调用按钮时调用的方法中。
编辑:As requested here's a simple Xcode project。
(注意:由于它是随机的,你可能会得到相同的文字,因此可能看起来文本没有改变,但确实如此,但它改变为与之前没有看到的相同的文本)
答案 1 :(得分:0)
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
//Create window
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[_window makeKeyAndVisible];
sampleArray = [[NSArray arrayWithObjects: @"iPhone", @"iPod", @"iMac", @"Newton",@"iPad",@"Lisa",@"Mac mini",@"Delta" ,nil] retain];
randButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[randButton setFrame:CGRectMake(20.0f, 30.0f, 60.0f, 40.0f)];
[randButton setTitle:@"Random" forState:UIControlStateNormal];
[randButton addTarget:self action:@selector(randNumberGenerate) forControlEvents:UIControlEventTouchUpInside];
[_window addSubview:randButton];
}
- (void) randNumberGenerate
{
NSString* string = [sampleArray objectAtIndex:(arc4random()%[sampleArray count])];
UILabel* displayRandNum = [[UILabel alloc] initWithFrame:CGRectMake(120.0f, 30.0f, 80.0f, 30.0f)];
displayRandNum.text = string;
[_window addSubview:displayRandNum];
[displayRandNum release];
}