如何在具有多个组件的UIPickerView中为特定组件添加图像?

时间:2014-09-28 21:16:52

标签: ios objective-c ios7 uipickerview

我已经花了好几个小时来添加一个包含4个组件的UIPickerView。其中三个组件应显示来自三个不同NSArray的字符串数据,但对于第四个组件,我试图添加图像。

在另一个SO-thred中我读到了这个方法:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
   // return aUIView;
}

返回UIViews,在我的例子中是一个ImageView。

我设法显示存储在我的i​​mages数组中的imagesViews,但前提是我的picker视图中有一个组件。

我如何将其与其他三个不应返回UIView的组件相结合,而只是将一些字符串值组合在一起?

到目前为止,这是我.m所得到的:

- (void)viewDidLoad
{
    [super viewDidLoad];

   // Four Arrays with some data
    self.contractLevelArray = ...someStringObjects... 
    self.imageViewsWithImagesForSuitArray =...someUIImageViewObjectsWithImages...
    self.doubleOrRedoubleArray = ...someStringObjects...
    self.contractByPlayerArray = ...someStringObjects...
}

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

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

    if (component == 0) {
        return self.contractLevelArray.count;
    } else if (component == 1) {
        return self.imageViewsWithImagesForSuitArray.count;
    } else if (component == 2) {
        return self.contractByPlayerArray.count;
    } else {
        return self.doubleOrRedoubleArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{

    if (component == 0) {
        return [self.contractLevelArray objectAtIndex:row];
    } else if (component == 1) {


        // For this component i want to return the UIImageViews for my images


    } else if (component == 2) {
        return [self.contractByPlayerArray objectAtIndex:row];
    } else {
        return [self.doubleOrRedoubleArray objectAtIndex:row];
    }

}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    // self.myImages is an array of UIImageView objects
    UIView *myView = [self.imageViewsWithImagesForSuitArray objectAtIndex:row];

    // first convert to a UIImage
    UIGraphicsBeginImageContextWithOptions(myView.bounds.size, NO, 0);

    [myView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    // then convert back to a UIImageView and return it
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    return imageView;
}

1 个答案:

答案 0 :(得分:1)

您不能同时使用viewForRowtitleForRow。在您的情况下,只使用viewForRow

对于图像组件,返回图像视图。对于其他人,请返回带有所需文本的标签。