Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS7 UIPickerView doesn't properly display custom views with images

This issue started happening in iOS7 with the new UIPickerView controller. To use images in your UIPickerView controller you must use the delegate method to return an image:

pickerView:viewForRow:forComponent:reusingView:

The problem is that the screen subsequently exhibits all kinds of strange behavior - the image views disappear as you move your finger up and down the control.

like image 946
Ed Trujillo Avatar asked Oct 03 '13 11:10

Ed Trujillo


2 Answers

This is a solution posted on a dev forum which works as of iOS 7.0.2:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    // self.myImages is an array of UIImageView objects
    UIView * myView = [self.myImages 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;
}
like image 182
Ed Trujillo Avatar answered Nov 09 '22 23:11

Ed Trujillo


There is a far simpler way to do it than Ed Trujilo's method (It assumes you are using UIImageView's however ... Ed's method should work for any UIView, I believe).

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    return [[UIImageView alloc] initWithImage: [mpSelections[row] image]];
}
like image 23
Goz Avatar answered Nov 09 '22 22:11

Goz