5

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.

Ed Trujillo
  • 1,371
  • 11
  • 9
  • There is a slightly simpler way of doing it than your answer. Not quite good enough for me, but has pointed me in the right direction. – Goz Mar 11 '14 at 11:45
  • I found a description of the problem which gives a bit more detail about what's meant by the UIPickerView not displaying "properly": There are two problems. First, the image views disappear when you move your finger up and down the control. Second, nothing can be shown in the selection area (the middle stripe), it is blank. Source: [link](http://forums.xamarin.com/discussion/9138/ios7-uipickerview-not-display-custom-views-with-images) – Michael Osofsky May 04 '14 at 00:53

2 Answers2

13

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;
}
Ed Trujillo
  • 1,371
  • 11
  • 9
3

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]];
}
Goz
  • 61,365
  • 24
  • 124
  • 204
  • This solution from @Goz worked for me. But it took me a while to understand the solution. The important aspect seems to be that you have to instantiate a new `UIImageView` and put the image into it. Before I understood this, I was just returning a `UIImageView` that was cached on an array. – Michael Osofsky May 04 '14 at 00:57