Tuesday, June 4, 2013

UIScrollView zooming example in Objective C (iOS).


UIScrollView zooming

A Boolean value that indicates whether the content view is currently zooming in or out. (read-only)

@property(nonatomic, readonly, getter=isZooming) BOOL zooming

Discussion of [UIScrollView zooming]
The value of this property is YES if user is making a zoom gesture, otherwise it is NO .

UIScrollView zooming example.
Just create a view, add all subviews to this view and add the newly created view as a single subview to the scrollview...

Then in the viewForZoomingInScrollView delegate method return the object at Index 0:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return [self.scrollView.subviews objectAtIndex:0];
}

Example of [UIScrollView zooming].
// Return the view that you want to zoom. My UIView is named contentView.
-(UIView*) viewForZoomingInScrollView:(UIScrollView*)scrollView {
  return self.contentView;
}

// Recursively find all views that need scaled to prevent blurry text
-(NSArray*)findAllViewsToScale:(UIView*)parentView {
    NSMutableArray* views = [[[NSMutableArray alloc] init] autorelease];
    for(id view in parentView.subviews) {

        // You will want to check for UITextView here. I only needed labels.
        if([view isKindOfClass:[UILabel class]]) {
            [views addObject:view];
        } else if ([view respondsToSelector:@selector(subviews)]) {
            [views addObjectsFromArray:[self findAllViewsToScale:view]];
        }
    }
    return views;
}

// Scale views when finished zooming
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
    CGFloat contentScale = scale * [UIScreen mainScreen].scale; // Handle retina

    NSArray* labels = [self findAllViewsToScale:self.contentView];
    for(UIView* view in labels) {
        view.contentScaleFactor = contentScale;
    }
}

UIScrollView zooming example.
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
  return self.theImageView;
}

- (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andUIView:(UIView *)rView {
  CGSize boundsSize = scroll.bounds.size;
  CGRect frameToCenter = rView.frame;
  // center horizontally
  if (frameToCenter.size.width < boundsSize.width) {
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
  }
  else {
    frameToCenter.origin.x = 0;
  }
  // center vertically
  if (frameToCenter.size.height < boundsSize.height) {
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
  }
  else {
    frameToCenter.origin.y = 0;
  }
  return frameToCenter;
}

-(void)scrollViewDidZoom:(UIScrollView *)scrollView
{
  self.theImageView.frame = [self centeredFrameForScrollView:self.theScrollView andUIView:self.theImageView];                              
}

End of UIScrollView zooming example article.