This is what I want:
How do I randomly select an object from the arrays I have to populate the first three columns of my UIPicker. I want the last two columns to remain unaffected by this action. So when the user clicks "generate" button, they will put random objects into the first three columns of my picker. Here is what I have:
- (void)viewDidLoad
{
self.column1Array = [[NSArray alloc] initWithObjects:
@"+10", @"+9", @"+8", @"+7", @"+6", @"+5", @"+4", @"+3", @"+2", @"+1", @"0", @"-1", @"-2", @"-3", @"-4", @"-5", @"-6", @"-7", @"-8", @"-9",
@"-10", nil];
self.column2Array = [[NSArray alloc] initWithObjects:开发者_开发技巧
@"+", @"-", nil];
self.column3Array = [[NSArray alloc] initWithObjects:
@"+10", @"+9", @"+8", @"+7", @"+6", @"+5", @"+4", @"+3", @"+2", @"+1", @"0", @"-1", @"-2", @"-3", @"-4", @"-5", @"-6", @"-7", @"-8", @"-9",
@"-10",nil];
self.column4Array = [[NSArray alloc] initWithObjects:
@"=", nil];
self.column5Array = [[NSArray alloc] initWithObjects:
@"+20", @"+19", @"+18", @"+17", @"+16", @"+15", @"+14", @"+13", @"+12",
@"+11", @"+10", @"+9", @"+8", @"+7", @"+6", @"+5", @"+4", @"+3", @"+2",
@"+1", @"0", @"-1", @"-2", @"-3", @"-4", @"-5", @"-6", @"-7", @"-8", @"-9",
@"-10",@"-11", @"-12", @"-13", @"-14", @"-15", @"-16", @"-17", @"-18",
@"-19", @"-20", nil];
[super viewDidLoad];
}
This should work, I haven't tested it though. This also assumes your UIPicker is called picker.
int column1Random = (arc4random() % [colum1Array count])-1;
[picker selectRow:column1Random inComponent:0 animated:YES];
int column2Random = (arc4random() % [colum2Array count])-1;
[picker selectRow:column2Random inComponent:1 animated:YES];
int column3Random = (arc4random() % [colum3Array count])-1;
[picker selectRow:column3Random inComponent:2 animated:YES];
You Need to Update the pickerView:numberOfRowsInComponents and the pickerView:titleForRows:forComponents methods
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent :(NSInteger)component
{
if (component==0) {
return [column1Array count];
} else if (component==1){
return[column2Array count];
} else if (component==2){
return[column32Array count];
} else if (component==3){
return[column4Array count];
} else {
return[column5Array count];
}
}
// Method to show the title of row for a component.
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (component)
{
case 0:
return [column1Array objectAtIndex:row];
break;
case 1:
return [column2Array objectAtIndex:row];
break;
case 2:
return [column3Array objectAtIndex:row];
break;
case 3:
return [column4Array objectAtIndex:row];
break;
case 4:
return [column5Array objectAtIndex:row];
break;
}
return nil;
}
精彩评论