views:

374

answers:

2

To support zooming a image in a UIScrollView, I thought I have to conform the MyController to the UIScrollViewDelegate like as follows. But it works fine without conforming to the UIScrollViewDelegate, even though compiler generates a following warning message.
warning: class 'MyController' does not implement the 'UIScrollViewDelegate' protocol

Isn't it mandatory to conform to the UIScrollViewDelegate in a header file?
Are there any side-effects if I forget to conform?

//@interface MyController : UIViewController <UIScrollViewDelegate>
@interface MyController : UIViewController
{
    UIScrollView *scrollView;
    UIImageView *imageView;
}
@end

@implementation HelloController
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

- (void)loadView
{
    UIImage *img = [UIImage imageNamed:@"foo.png"];
    imageView = [[UIImageView alloc] initWithImage:img];
    imageView.userInteractionEnabled = NO;

    scrollView = [[UIScrollView alloc] initWithFrame: [[UIScreen mainScreen] applicationFrame]];
    [scrollView setScrollEnabled:YES];
    [scrollView setContentSize:[imageView size]];
    [scrollView setMaximumZoomScale:2.0f];
    [scrollView setMinimumZoomScale:0.5f];
    [scrollView setDelegate:self];

    [scrollView addSubview:imageView];

    self.view = scrollView;
    [scrollView release];
}
@end
+1  A: 

Replace this line:

[scrollView setDelegate:self];

with this:

[scrollView setDelegate:(id<UIScrollViewDelegate>)self];

Still, I don't know why the compiler isn't recognizing that you have implemented UIScrollViewDelegate

edit: to satisfy the compiler, you can also implement the protocol on a private category defined in your .m file:

@interface FormModel () <UIScrollViewDelegate>
@end
rpetrich
I'm sorry I wasn't able to explain my question well. I modified my code a bit, but my question is why this code works fine without conforming to the UIScrollViewDelegate in the header file.
tomute
Ah, I missed your edit. You can also add an empty category to your .m file: @interface FormModel () <UIScrollViewDelegate>@end
rpetrich
A: 

If your class actually implements the delegate methods, you won't get any errors because they will be actually called when required.

Conforming to the protocol just tells the compiler that this class implements those methods. So by omitting it, the compiler will generate a warning because you assign the UIScrollView.delegate to a class that does not seem to conform to the UIScrollViewDelegate protocol as required.

Dimitris
Thank you for your answer. That makes sense to me. But, if I assign the delegate via Interface Builder, Interface Builder doesn't complain at all. That's interesting behavior. Anyway, thanks again!
tomute