Using UIPickerView to display different images upon selection in UIImageView

淺唱寂寞╮ 提交于 2019-12-11 10:42:36

问题


I have a UIPickerView filled with an array of tree types. I also have an empty UIImageView below that I would like to change upon the selection of the picker view. I got a label to change with the selection but cannot get images to change. Here is what I have so far

EDIT EDIT : Now working! Correct Code below

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    dataArray = [[NSArray alloc]initWithObjects:@"Birch", @"Elm", @"Maple", @"Oak", @"White Pine",@"Willow", nil];
    myPicker.delegate = self;
    imageArray = [[NSArray alloc]initWithObjects:@"birch_river.png",@"elm_american.png",@"maple_bigtooth.png", @"oak_bur.png", @"white_pine.png", @"oak_willow.png", nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [dataArray count];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    myLabel.text = [dataArray objectAtIndex:row];
    myImage.image = [UIImage imageNamed:[imageArray objectAtIndex:row]];
}

 -(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:  (NSInteger)component
{
    return [dataArray objectAtIndex:row];
}


@end

回答1:


What you can do is, have an array filled with the image names (Ex: IMAGES_ARRAY with image names).

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:   (NSInteger)component
{
    myLabel.text = [dataArray objectAtIndex:row];
    YOUR_IMG_VIEW = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[IMAGES_ARRAY ObjectAtIndex.row]]];
}


来源:https://stackoverflow.com/questions/22309964/using-uipickerview-to-display-different-images-upon-selection-in-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!