问题
I'm trying to create an array that holds x amount of literal strings that will randomly send one to a UILabel after you hit a UIButton.
How should I structure the .h and .m files to do this? Also, what is the best way to generate the random number I need?
回答1:
You would get a random integer for the index, and then just pass the object you get to the UILabel's text property, eg:
//assuming you already have an NSArray of strings
myLabel.text = [arrayOfString objectAtIndex:arc4random() % [arrayOfString count]];
You'd put the above code in the method that the button calls when it's pressed.
EDIT: As requested here's a simple Xcode project.
(NOTE: As it's random there's a chance that you'll get the same text so it may appear that the text doesn't change, it does but it changes to the same text as before which you don't see)
回答2:
- (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];
}
来源:https://stackoverflow.com/questions/4889551/random-text-sent-to-uilabel