views:

46

answers:

3

In the following code I have a view object that is an instance of UIScrollView, if I run the code below I get warnings saying that "UIView might not respond to -setContentSize etc."

UIImage *image = [UIImage imageNamed:@"Snowy_UK.jpg"];
imageView = [[UIImageView alloc] initWithImage:image];
[[self view] addSubview:imageView];
[[self view] setContentSize:[image size]];
[[self view] setMaximumZoomScale:2.0];
[[self view] setMinimumZoomScale: [[self view] bounds].size.width / [image size].width];

I have checked the type of the object and [self view] is indeed a UIScrollView. I am guessing that this is just the compiler making a bad guess as to the type and the solution is simply to cast the object to the correct type manually, am I getting this right?

UIScrollView *scrollView = (UIScrollView *)[self view];

UIImage *image = [UIImage imageNamed:@"Snowy_UK.jpg"];
imageView = [[UIImageView alloc] initWithImage:image];
[[self view] addSubview:imageView];
[scrollView setContentSize:[image size]];
[scrollView setMaximumZoomScale:2.0];
[scrollView setMinimumZoomScale: [scrollView bounds].size.width / [image size].width];

cheers Gary.

+3  A: 

If you defined the instance variable in a class of your own, you can of course declare it as: UIScrollView *view; inside the class definition. If you've subclassed another class that has UIView *view; in the definition (I suspect that's the case here), then the way you're doing it above is probably the best way to satisfy the compiler.

You might also want to add an assert to check the class of the view at that point, so you get a reasonable error message if something goes wrong.

Mark Bessey
Hi Mark, I setup a UIViewController in IB, deleted the view and replaced it with a UIScrollView. When I go to reconnect the fileOwner to my new UIScrollView I have to do it by using view, which is essentially why later the compiler thinks its a view and not a scrollView. Thanks for the tip, that works nicely.
fuzzygoat
+1  A: 

UIScrollView inherits from UIView, so changing your calls to something like this should work:

[self addSubview:imageView];

John

iOSDevelopertips.com

John
A: 

The compiler does not guess the type, it uses the type that you declare. self.view must be a UIView and that is why you get a warning when you try to setContentSize, because you declare that view is a UIView.

When you cast you tell the compiler, this is really a UIScrollView, so it no longer gives the warning. If it really is a UIScrollView all the time, then your view property should be declared a UIScrollView.

progrmr