I give up. Can’t seem to make this very basic thing work. Please help…
I’m trying to load an image from a URL onto a scrollable, pinch/zoomable screen.
Here’s my code snippet which yields a blank white screen. I’ve chosen to place it in viewDidAppear:
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIImageView *imageView;
…
- (void)viewDidAppear:(BOOL)animated {
NSData *photoData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlForImage]];
UIImage *photoImage = [[UIImage alloc] initWithData:photoData];
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
[self.scrollView setContentSize:photoImage.size];
[self.scrollView setMinimumZoomScale:1];
[self.scrollView setMaximumZoomScale:5];
[self.view addSubview:self.scrollView];
self.imageView = [[UIImageView alloc] initWithImage:photoImage];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.imageView setFrame:self.view.frame];
[self.scrollView addSubview:self.imageView];
}
I’ve also implemented viewForZoomingInScrollView:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
I’m getting a white screen. What am I missing? Thank you in advance.
As @jonkroll suggests, the problem is that you’re assigning a retained object to a weak variable. It’s not like a IBOutlet, which should generally be weak. Here you definitely want to change it to strong and it should fix your problem.
To demonstrate the current problem, if you put the following statement immediately after you alloc/init statements for the scrollView, for example, you may be surprised to see it’s nil, because ARC has already released it for you, e.g.:
Make them strong, and you’re ok. If you replace your self.scrollView and self.imageView with just scrollView and imageView, you’ll probably see the compiler warnings.
Alternatively, if you don’t need these vars for other reasons, you can also forget about making them properties at all and make them local vars of the viewDidLoad method (the views themselves will be retained when you add them as subviews … no reason to make them properties or ivars unless you need the vars for some reason in some other method). I don’t like to add properties or ivars unless I need to. If you need them, fine, you need them, but if you don’t, make them local viewDidLoad vars.