0

I've trying to create my own ScrollableImageView like this:

@interface ZoomableImageScrollView : UIScrollView <UIScrollViewDelegate>

@property (strong, nonatomic) UIImageView *imageView;
- (void)setImage:(UIImage *)image;

@end

@implementation ZoomableImageScrollView

- (void)awakeFromNib
{
    self.imageView = [[UIImageView alloc] initWithFrame:self.bounds];

    // Finally
    [self addSubview:self.imageView];
    self.delegate = self;
}

- (void)setImage:(UIImage *)image
{
    self.imageView.image = image;
    self.imageView.frame = (CGRect){.origin = CGPointZero, .size = image.size};
    self.contentSize = image.size;

    CGRect scrollViewFrame = self.frame;
    CGFloat scaleWidth = scrollViewFrame.size.width / self.contentSize.width;
    CGFloat scaleHeight = scrollViewFrame.size.height / self.contentSize.height;
    CGFloat minScale = MIN(scaleWidth, scaleHeight);

    self.minimumZoomScale = minScale;
    self.maximumZoomScale = 4;
    self.zoomScale = 1;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    NSLog(@"start!!");
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    NSLog(@"here!!");
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    NSLog(@"DidZoom");
}

@end

And then, I create this scrollView in other viewControllers, set image, trying to zoom, but it never ran into the 3 last delegate's method. Can someone explain why this won't work? If I use these lines in that viewController, it actually does. Does that mean UIView can't implement some protocols but only the viewController does?

Finally, what is the best practice to utilize these kinds of things? Like, I'd like to create the reusable Scrollable Image View.

Eddie
  • 1,903
  • 2
  • 21
  • 46
  • Do you pass into `awakeFromNib`? In `setImage:` what's the value of `self.delegate`? Didn't test, but is the user interaction enabled? I haven't played with `UIScrollView` for a while, but your `UIImageView` may block the user interactions. – Larme Jan 11 '16 at 17:23
  • Debugger got through `awakeFromNib`. In `setImage:` the value of `self.delegate` is really `self`. Also, I've turned on all the userInteractions. Even if `UIImageView` doesn't, it still should've worked. – Eddie Jan 11 '16 at 17:30

0 Answers0