这就是我想要的:
如何从数组中随机选择一个对象,我必须填充UIPicker的前三列。我希望最后两列不受此操作的影响。因此,当用户单击“生成”按钮时,他们会将随机对象放入我的选择器的前三列。这就是我所拥有的:
- (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];
}
答案 0 :(得分:1)
这应该可行,但我还没有测试过。这也假设你的UIPicker被称为选择器。
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];
您需要更新pickerView:numberOfRowsInComponents和pickerView:titleForRows:forComponents方法
- (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;
}