你当然可以这样做。首先,将图像链接和食物名称存储在一个数组中会更好。这将使您的应用程序更具可扩展性,并且对代码的更改不太可能导致错误。
你可以这样做:
food = [[NSMutableArray alloc] init];
[food insertObject:[NSMutableArray arrayWithObjects:@"Pasta",@"Pasta.png",nil] atIndex:[food count]];
[food insertObject:[NSMutableArray arrayWithObjects:@"Pizza",@"Pizza.png",nil] atIndex:[food count]];
虽然如果你的图片和你的名字一样但是扩展名为 .png 那么你真的需要两个对象吗?
至于为 a 设置图像,UIPicker
你会做这样的事情(你需要添加UIPickerViewDelegate
到 .h 并调用[self setPickerValue];
你想显示的地方UIPicker
- 也许是一个按钮或文本字段?):
-(void)setPickerValue {
pickerActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
[pickerActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 44, 0, 0);
UIPickerView *valuesPicker = [[UIPickerView alloc] initWithFrame:pickerFrame];
[valuesPicker setDataSource: self];
[valuesPicker setDelegate: self];
valuesPicker.showsSelectionIndicator = YES;
[pickerActionSheet addSubview:valuesPicker];
UIToolbar *controlToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[controlToolBar setBarStyle:UIBarStyleBlack];
[controlToolBar sizeToFit];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *setButton = [[UIBarButtonItem alloc] initWithTitle:@"Set" style:UIBarButtonItemStyleDone target:self action:@selector(dismissPicker)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelPicker)];
[controlToolBar setItems:[NSArray arrayWithObjects:cancelButton, spacer, setButton, nil] animated:NO];
[pickerActionSheet addSubview:controlToolBar];
[pickerActionSheet showInView:self.view];
[pickerActionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(void)cancelPicker {
[pickerActionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
// Number of components.
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [food count];
}
// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [[food objectAtIndex: row] objectAtIndex:0];
}
上面的代码创建了一个不错的选择器视图,其中带有一个取消和确定按钮作为工具栏。您需要的最后一个功能是(假设您有一个UIButton
名为“button1”):
-(void)dismissPicker {
[button1 setImage:[UIImage imageNamed: [[food objectAtIndex:row] objectAtIndex:1]] forState:UIControlStateNormal];
[pickerActionSheet dismissWithClickedButtonIndex:0 animated:YES];
}