Hey I'm following this tutorial and currently on the first step but am experiencing some weird behavior. The tutorial is on creating scroll views for images and ends with showing how to create a paged horizontal ScrollView with a page controller. I followed the first section and things seemed to be working fine. However when I ran the code it did not perform properly, after about an hour of debugging I downloaded the final project, ran it on my phone to check if it was working correctly (it was) then copied the code into the required files in my project. My project still wouldn't run. So I figured it must be the way in which my story board was configured on the project setup. I then oped the working example cleared their storyboard and created the views and segues my self, in the exact same way and order I had done in my project. Bam! it still worked, when I deleted all views in my story board and recreated them in the exact same fashion, still nothing. Could someone look into this tutorial and tell me if I'm going crazy or they experience similar results. I have narrowed it down to two possibilities, the project provided at the end of the tutorial was created differently and the delegates or outlets were hooked up in a way that only works with the project, or the project was created with an earlier version of the iPhone development kit that works with the current version of XCode but not when I create a new project. Then again I am fairly new to this so I will throw up the code I'm using and hope for the best.
ViewController.h file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIScrollViewDelegate>
#property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
#end
ViewController.m file:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) UIImageView *imageView;
- (void)centerScrollViewContents;
- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer;
- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer;
#end
#implementation ViewController
#synthesize scrollView = _scrollView;
#synthesize imageView = _imageView;
- (void)centerScrollViewContents {
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.imageView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.imageView.frame = contentsFrame;
}
- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer {
// Get the location within the image view where we tapped
CGPoint pointInView = [recognizer locationInView:self.imageView];
// Get a zoom scale that's zoomed in slightly, capped at the maximum zoom scale specified by the scroll view
CGFloat newZoomScale = self.scrollView.zoomScale * 1.5f;
newZoomScale = MIN(newZoomScale, self.scrollView.maximumZoomScale);
// Figure out the rect we want to zoom to, then zoom to it
CGSize scrollViewSize = self.scrollView.bounds.size;
CGFloat w = scrollViewSize.width / newZoomScale;
CGFloat h = scrollViewSize.height / newZoomScale;
CGFloat x = pointInView.x - (w / 2.0f);
CGFloat y = pointInView.y - (h / 2.0f);
CGRect rectToZoomTo = CGRectMake(x, y, w, h);
[self.scrollView zoomToRect:rectToZoomTo animated:YES];
}
- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer {
// Zoom out slightly, capping at the minimum zoom scale specified by the scroll view
CGFloat newZoomScale = self.scrollView.zoomScale / 1.5f;
newZoomScale = MAX(newZoomScale, self.scrollView.minimumZoomScale);
[self.scrollView setZoomScale:newZoomScale animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Set a nice title
self.title = #"Image";
// Set up the image we want to scroll & zoom and add it to the scroll view
UIImage *image = [UIImage imageNamed:#"photo1.png"];
self.imageView = [[UIImageView alloc] initWithImage:image];
self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size};
[self.scrollView addSubview:self.imageView];
// Tell the scroll view the size of the contents
self.scrollView.contentSize = image.size;
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewDoubleTapped:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.numberOfTouchesRequired = 1;
[self.scrollView addGestureRecognizer:doubleTapRecognizer];
UITapGestureRecognizer *twoFingerTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewTwoFingerTapped:)];
twoFingerTapRecognizer.numberOfTapsRequired = 1;
twoFingerTapRecognizer.numberOfTouchesRequired = 2;
[self.scrollView addGestureRecognizer:twoFingerTapRecognizer];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Set up the minimum & maximum zoom scales
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
self.scrollView.minimumZoomScale = minScale;
self.scrollView.maximumZoomScale = 1.0f;
self.scrollView.zoomScale = minScale;
[self centerScrollViewContents];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
// Return the view that we want to zoom
return self.imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
// The scroll view has zoomed, so we need to re-center the contents
[self centerScrollViewContents];
}
#end
The above code doesn't work as it does in the tutorials project. The following UIScrollView delegate method viewForZoomingInScrollView produces this error:
2013-05-14 10:01:18.585 TestScrollView[3809:907] Made it
May 14 10:01:18 Scott-Laroses-iPhone TestScrollView[3809] : CGAffineTransformInvert: singular matrix.
May 14 10:01:18 Scott-Laroses-iPhone TestScrollView[3809] : CGAffineTransformInvert: singular matrix.
which makes me think the delate isn't properly set up despite me doing it exactly the same as in the tutorial and programmatically when that didn't work. Any ideas?
Your problem may be from the zoomScale and minimumZoomScale if the value assigned is 0. Make sure that the value is never 0 for those two properties.
I figured it out! The issues was that the auto layout constraints were messing up the off screen views. So I disabled auto layout and it worked fine.
Related
I'm a beginner with iOS, so i'm just not sure what to research here. I have a UIScrollView with a few square subViews added. How can i make the subviews smaller as they scroll off screen and bigger as they approach the center of the screen?
#import "HorizontalScrollMenuViewController.h"
#import <UIKit/UIKit.h>
#define SUBVIEW_WIDTH_HEIGHT 280
#interface HorizontalScrollMenuViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
#end
#implementation HorizontalScrollMenuViewController
-(void)viewDidLoad{
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor greenColor],[UIColor redColor],[UIColor orangeColor],[UIColor blueColor],nil ];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat originX = (screenWidth - SUBVIEW_WIDTH_HEIGHT)/2.0; // get margin to left and right of subview
CGFloat originY = ((screenHeight - SUBVIEW_WIDTH_HEIGHT)/2);
// add subviews of all activities
for (int i = 0; i < colors.count; i++){
CGRect frame = CGRectMake(0,0,SUBVIEW_WIDTH_HEIGHT,SUBVIEW_WIDTH_HEIGHT);
frame.origin.x = self.scrollView.frame.size.width * i + originX;
frame.origin.y = originY;
UIView *subView = [[UIView alloc] initWithFrame:frame];
[UIView setAnimationBeginsFromCurrentState: YES];
subView.layer.cornerRadius = 15;
subView.layer.masksToBounds = YES;
subView.backgroundColor = [colors objectAtIndex:i];
[self.scrollView addSubview:subView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
Here you can find a fully working example of what you're trying to accomplish. It only has
one subview because it's just to give you an idea of how can you accomplish it. Also, this example was tested on an iPad (iOS7) simulator.
The *.h file
#import <UIKit/UIKit.h>
// Remember to declare ourselves as the scroll view delegate
#interface TSViewController : UIViewController <UIScrollViewDelegate>
#property (nonatomic, strong) UIView *squareView;
#end
The *.m file
#import "TSViewController.h"
#implementation TSViewController
#synthesize squareView = _squareView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Create and configure the scroll view (light gray)
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(100, 100, 500, 500)];
CGRect contentSize = myScrollView.frame;
contentSize.size.height = contentSize.size.height + 400;
myScrollView.contentSize = contentSize.size;
myScrollView.userInteractionEnabled = YES;
// give the scroll view a gray color so it's easily identifiable
myScrollView.backgroundColor = [UIColor lightGrayColor];
// remember to set yourself as the delegate of the scroll view
myScrollView.delegate = self;
[self.view addSubview:myScrollView];
// Create and configure the square view (blue)
self.squareView = [[UIView alloc] initWithFrame:CGRectMake(200, 400, 60, 60)];
self.squareView.backgroundColor = [UIColor blueColor];
[myScrollView addSubview:self.squareView];
}
// Here is where all the work happens
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Get the difference between the contentOffset y position and the squareView y position
CGFloat y = self.squareView.frame.origin.y - scrollView.contentOffset.y;
// If the square has gone out of view, return
if (y <= 0) {
return;
}
// Modify the squareView's frame depending on it's current position
CGRect squareViewFrame = self.squareView.frame;
squareViewFrame.size.height = y + 5;
squareViewFrame.size.width = y + 5;
squareViewFrame.origin.x = (scrollView.contentSize.width - squareViewFrame.size.width) / 2.0;
self.squareView.frame = squareViewFrame;
}
#end
And here is a little explanation of what is going on:
A UIScrollView has several properties that allow you to configure it correctly. For example it has a frame (gray) which is inherited from UIView; with this property you specify the visible size of the scroll view. It also has the contentSize (red) which specifies the total size of the scroll view; in the image it's showed as the red area but this is only for illustration purposes as it will not be visible in the program. Imagine the scroll view's frame as the window that let's you see only a part of the bigger content the scroll view has.
When the user starts scrolling a gap appears between the top part of the contentSize and the top part of the frame. This gap is known as the contentOffset
Here is the reference to UIScrollView
Here is the reference to UIScrollViewDelegate
Hope this helps!
Assuming that you have the scrollView inside self.view, you can implement scrollViewDidScroll: in the scroll view delegate to find when it is scrolled.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
for (UIView *view in self.scrollView.subviews) {
CGRect frame = [view convertRect:view.frame toView:self.view]; // Contains the frame of view with respect to self.view
}
}
You can them use the frame to resize subviews as you want.
The answer starts with analyzing the UIScrollView Class Reference and it's delegate. In the delegate documentation see the responding to scrolling and dragging section. You should also review the sample code for each. You can create outlets to your subviews and change the subview properties within a uiview animation. These references will give you a good foundation in understanding where you can build the call to animate the subviews.
Here is a link to animating subviews. Additional examples can be found by Googling "uiview subview animation" (without the quotes). If you run into any major issues read the header files first and post some sample code for additional (more precise) help.
Other reference:
UIKit ScrollViews
I have an uipageviewcontroller and set a child viewcontroller in uipageviewcontroller named as contentviewcontroller.
thePageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation: UIPageViewControllerNavigationOrientationHorizontal options:nil];
thePageViewController.delegate = self;
thePageViewController.dataSource = self;
thePageViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
contentViewController = [[HBDocumentChildViewController alloc] initWithPDF:PDFDocument];
contentViewController.page = [modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[thePageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:thePageViewController];
[self.view addSubview:thePageViewController.view];
thePageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[thePageViewController didMoveToParentViewController:self];
self.view.gestureRecognizers = thePageViewController.gestureRecognizers;
self.view.backgroundColor = [UIColor underPageBackgroundColor];
I had done to load pdf files into pages in uipageviewcontroller with the help of a scroll view class(pdfScrollView).The followig is the content class of uipageviewcontroller and initializing the uiscrollview class.
#import "HBDocumentChildViewController.h"
#interface HBDocumentChildViewController ()<UIWebViewDelegate>
{
int currentPage;
NSString*localPath;
}
#end
#implementation HBDocumentChildViewController
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Create our PDFScrollView and add it to the view controller.
CGPDFPageRef PDFPage = CGPDFDocumentGetPage(thePDF, [_page intValue]);
pdfScrollView = [[PDFScrollView alloc] initWithFrame:self.view.frame];
[pdfScrollView setPDFPage:PDFPage];
[self.view addSubview:pdfScrollView];
self.view.backgroundColor = [UIColor whiteColor];
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
pdfScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
The following is the uiscrollview class,
/*
File: PDFScrollView.m
Abstract: UIScrollView subclass that handles the user input to zoom the PDF page. This class handles swapping the TiledPDFViews when the zoom level changes.
Version: 2
*/
#import "PDFScrollView.h"
#import "TiledPDFView.h"
#import <QuartzCore/QuartzCore.h>
#interface PDFScrollView ()
// A low resolution image of the PDF page that is displayed until the TiledPDFView renders its content.
#property (nonatomic, weak) UIImageView *backgroundImageView;
// The TiledPDFView that is currently front most.
#property (nonatomic, weak) TiledPDFView *tiledPDFView;
// The old TiledPDFView that we draw on top of when the zooming stops.
#property (nonatomic, weak) TiledPDFView *oldTiledPDFView;
#end
#implementation PDFScrollView
{
CGPDFPageRef _PDFPage;
// Current PDF zoom scale.
CGFloat _PDFScale;
CGFloat _PDFScaleH;
}
#synthesize backgroundImageView=_backgroundImageView, tiledPDFView=_tiledPDFView, oldTiledPDFView=_oldTiledPDFView;
- (id)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
self.decelerationRate = UIScrollViewDecelerationRateFast;
self.delegate = self;
}
return self;
}
- (void)setPDFPage:(CGPDFPageRef)PDFPage;
{
CGPDFPageRetain(PDFPage);
CGPDFPageRelease(_PDFPage);
_PDFPage = PDFPage;
// Determine the size of the PDF page.
CGRect pageRect = CGPDFPageGetBoxRect(_PDFPage, kCGPDFMediaBox);
float actualHeight = pageRect.size.height;
float actualWidth = pageRect.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 768.0/911.0;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 911.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 911.0;
}
else{
imgRatio = 768.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 768.0;
}
}
pageRect.size = CGSizeMake(actualWidth, actualHeight);
UIGraphicsBeginImageContext(pageRect.size);
/*
Create a low resolution image representation of the PDF page to display before the TiledPDFView renders its content.
*/
UIGraphicsBeginImageContext(pageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// First fill the background with white.
CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context,pageRect);
CGContextSaveGState(context);
// Flip the context so that the PDF page is rendered right side up.
CGContextTranslateCTM(context, 0.0, pageRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Scale the context so that the PDF page is rendered at the correct size for the zoom level.
CGContextScaleCTM(context, imgRatio,imgRatio);
CGContextDrawPDFPage(context, _PDFPage);
CGContextRestoreGState(context);
UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (self.backgroundImageView != nil) {
[self.backgroundImageView removeFromSuperview];
}
UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];
backgroundImageView.frame = pageRect;
backgroundImageView.contentMode = UIViewContentModeScaleAspectFit;
[self addSubview:backgroundImageView];
[self sendSubviewToBack:backgroundImageView];
self.backgroundImageView = backgroundImageView;
// Create the TiledPDFView based on the size of the PDF page and scale it to fit the view.
TiledPDFView *tiledPDFView = [[TiledPDFView alloc] initWithFrame:pageRect scale:imgRatio];
[tiledPDFView setPage:_PDFPage];
[self addSubview:tiledPDFView];
self.tiledPDFView = tiledPDFView;
}
- (void)dealloc
{
// Clean up.
CGPDFPageRelease(_PDFPage);
}
#pragma mark -
#pragma mark Override layoutSubviews to center content
// Use layoutSubviews to center the PDF page in the view.
- (void)layoutSubviews
{
[super layoutSubviews];
// Center the image as it becomes smaller than the size of the screen.
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = self.tiledPDFView.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;
self.tiledPDFView.frame = frameToCenter;
self.backgroundImageView.frame = frameToCenter;
/*
To handle the interaction between CATiledLayer and high resolution screens, set the tiling view's contentScaleFactor to 1.0.
If this step were omitted, the content scale factor would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale.
*/
self.tiledPDFView.contentScaleFactor = 1.0;
}
#pragma mark -
#pragma mark UIScrollView delegate methods
/*
A UIScrollView delegate callback, called when the user starts zooming.
Return the current TiledPDFView.
*/
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.tiledPDFView;
}
/*
A UIScrollView delegate callback, called when the user begins zooming.
When the user begins zooming, remove the old TiledPDFView and set the current TiledPDFView to be the old view so we can create a new TiledPDFView when the zooming ends.
*/
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
// Remove back tiled view.
[self.oldTiledPDFView removeFromSuperview];
// Set the current TiledPDFView to be the old view.
self.oldTiledPDFView = self.tiledPDFView;
[self addSubview:self.oldTiledPDFView];
}
/*
A UIScrollView delegate callback, called when the user stops zooming.
When the user stops zooming, create a new TiledPDFView based on the new zoom level and draw it on top of the old TiledPDFView.
*/
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
// Set the new scale factor for the TiledPDFView.
_PDFScale *= scale;
// Calculate the new frame for the new TiledPDFView.
CGRect pageRect = CGPDFPageGetBoxRect(_PDFPage, kCGPDFMediaBox);
pageRect.size = CGSizeMake(pageRect.size.width*_PDFScale, pageRect.size.height*_PDFScale);
// Create a new TiledPDFView based on new frame and scaling.
TiledPDFView *tiledPDFView = [[TiledPDFView alloc] initWithFrame:pageRect scale:_PDFScale];
[tiledPDFView setPage:_PDFPage];
// Add the new TiledPDFView to the PDFScrollView.
[self addSubview:tiledPDFView];
self.tiledPDFView = tiledPDFView;
}
#end
The page rendering is working correctly,but i didn't get the zoom in/out in the page displayed view.The uiscrollview delegate method not working in uipageviewcontroller.Please help me to find the solution for this problem.
Try This
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(pinchDetected:)];
[thePageViewController addGestureRecognizer:pinchRecognizer];
pinchRecognizer.delegate=self;
The Method Is
-(void)pinchDetected:(UIPinchGestureRecognizer *)pinchRecognizer
{
CGFloat scale = pinchRecognizer.scale;
thePageViewController.transform = CGAffineTransformScale(thePageViewController.transform, scale, scale);
pinchRecognizer.scale = 1.0;
}
I have done the scroll and zoom in the uipageviewcontroller. I have changed the above UIPinchGestureRecognizer method for zoomIn and zoom out to the current page size.
-(void)pinchDetected:(UIPinchGestureRecognizer *)pinchRecognizer
{
if([pinchRecognizer state] == UIGestureRecognizerStateBegan) {
// Reset the last scale, necessary if there are multiple objects with different scales
lastScale = [pinchRecognizer scale];
}
if ([pinchRecognizer state] == UIGestureRecognizerStateBegan ||[pinchRecognizer state] == UIGestureRecognizerStateChanged)
{
CGFloat currentScale = [[[pinchRecognizer view].layer valueForKeyPath:#"transform.scale"] floatValue];
// Constants to adjust the max/min values of zoom
const CGFloat maxScale = 1.5;
const CGFloat minScale = 1.0;
CGFloat newScale = 1 - (lastScale - [pinchRecognizer scale]);
newScale = MIN(newScale, maxScale / currentScale);
newScale = MAX(newScale, minScale / currentScale);
thePageViewController.view.transform = CGAffineTransformScale(thePageViewController.view.transform, newScale, newScale);
lastScale = [pinchRecognizer scale]; // Store the previous scale factor for the next pinch gesture call
}
}
Then,I have added the [pdfScrollView setScrollEnabled:YES];,[pdfScrollView setContentSize:CGSizeMake(768, 1100)];code in the viewDidLoad of the content viewcontroller(HBDocumentChildViewController)for scrolling the contentview in the uipageviewcontroller class.
- (void)viewDidLoad
{
[super viewDidLoad];
// Create our PDFScrollView and add it to the view controller.
CGPDFPageRef PDFPage = CGPDFDocumentGetPage(thePDF, [_page intValue]);
pdfScrollView = [[PDFScrollView alloc] initWithFrame:self.view.frame];
pdfScrollView.bouncesZoom = YES;
[pdfScrollView setScrollEnabled:YES];
[pdfScrollView setContentSize:CGSizeMake(768, 1100)];
[pdfScrollView setPDFPage:PDFPage];
[self.view addSubview:pdfScrollView];
self.view.backgroundColor = [UIColor whiteColor];
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
pdfScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
pdfScrollView.delegate = pdfScrollView;
}
Try this code for zoomin and zoomout to the current page size and scrolling the content of the uipageviewcontroller.
This question may seem simple but please hear me out. I've made a huge mistake my project contains 300+ activities that are in a single storyboard and I've just recently figured out that Xcode is terrible at handling that. So what I would like to do is to have my different content which is now currently displayed in separate activities written into the code so that I only have to have the minimum amount of activities in my storyboard. This may be hard to follow I apologize.
In my head here is how it should work. I'l give an example.
In my app I have a section called MAPS, from the homepage you click on the maps button and it brings you to a menu which has buttons with the maps names on them. As you would expect the name of the map on the button brings you the the activity with said map. The problem is that each map is in a separate activity that is linked too inside the storyboard.
What I would like to do is programatically call each separate activity from within one activity in my storyboard effectively replacing 20+ activities with 1.
Here is what my map view controllers look like (they're actually .png images with a scrollview)
MapRoute1.h
#import "ViewController.h"
#interface MapRoute1 : ViewController <UIScrollViewDelegate>
#property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
#property (nonatomic, strong) UIImageView *imageView;
- (void)centerScrollViewContents;
- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer;
- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer;
#end
MapRoute1.m
#import "MapRoute1.h"
#interface MapRoute1 ()
#end
#implementation MapRoute1
#synthesize imageView = _imageView;
#synthesize scrollView = _scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)centerScrollViewContents {
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.imageView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.imageView.frame = contentsFrame;
}
- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer {
// 1
CGPoint pointInView = [recognizer locationInView:self.imageView];
// 2
CGFloat newZoomScale = self.scrollView.zoomScale * 1.5f;
newZoomScale = MIN(newZoomScale, self.scrollView.maximumZoomScale);
// 3
CGSize scrollViewSize = self.scrollView.bounds.size;
CGFloat w = scrollViewSize.width / newZoomScale;
CGFloat h = scrollViewSize.height / newZoomScale;
CGFloat x = pointInView.x - (w / 2.0f);
CGFloat y = pointInView.y - (h / 2.0f);
CGRect rectToZoomTo = CGRectMake(x, y, w, h);
// 4
[self.scrollView zoomToRect:rectToZoomTo animated:YES];
}
- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer {
// Zoom out slightly, capping at the minimum zoom scale specified by the scroll view
CGFloat newZoomScale = self.scrollView.zoomScale / 1.5f;
newZoomScale = MAX(newZoomScale, self.scrollView.minimumZoomScale);
[self.scrollView setZoomScale:newZoomScale animated:YES];
}
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
// Return the view that you want to zoom
return self.imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
// The scroll view has zoomed, so you need to re-center the contents
[self centerScrollViewContents];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 1
UIImage *image = [UIImage imageNamed:#"map_route1.png"];
self.imageView = [[UIImageView alloc] initWithImage:image];
self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size};
[self.scrollView addSubview:self.imageView];
// 2
self.scrollView.contentSize = image.size;
// 3
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewDoubleTapped:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.numberOfTouchesRequired = 1;
[self.scrollView addGestureRecognizer:doubleTapRecognizer];
UITapGestureRecognizer *twoFingerTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewTwoFingerTapped:)];
twoFingerTapRecognizer.numberOfTapsRequired = 1;
twoFingerTapRecognizer.numberOfTouchesRequired = 2;
[self.scrollView addGestureRecognizer:twoFingerTapRecognizer];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 4
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
self.scrollView.minimumZoomScale = minScale;
// 5
self.scrollView.maximumZoomScale = 1.5f;
self.scrollView.zoomScale = minScale;
// 6
[self centerScrollViewContents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
So as you can tell the only part that changes in each separate map is this line of code:
UIImage *image = [UIImage imageNamed:#"map_route1.png"];
What I would like to do is have some sort of list of all my images and when the button is clicked for that map(image) it will replace this line of code with the image name or Map that the button should link too. The overall code and everything should only be one activity in my storyboard that is linked to be each button in the MAPS menu.
Currently all activities are linked by a simple "control click-drag" in the storyboard and are contained inside of a navigation controller which provides back navigation.
I would like to keep the back navigation with the navigation controller but simply replace the image inside of the scrollview.
Thanks in advance!
-Derek
Note to casual readers: Despite the title, this question has nothing to do with the UIScrollView properties bounces (scrolling related) or bouncesZoom.
I am using UIScrollView to add zooming to a custom view. The custom view uses sublayers to draw its content. Each sublayer is a CALayer instance that is added to the view's main layer with [CALayer addSublayer:]. Sublayers use CoreGraphics to render their content.
After each zoom completes, the custom view needs to redraw its content at the new zoom scale so that the content appears crisp and sharp again. I am currently trying to get the
approach to work that is shown in this SO question, i.e. I reset the scroll view's zoomScale property to 1.0 after each zoom operation, then I adjust the minimumZoomScale and maximumZoomScale properties so that the user cannot zoom in/out more than originally intended.
The content redrawing already works correctly (!), but what I am missing is a smooth GUI update so that the zoomed content is redrawn in place without appearing to move. With my current solution (code example follows at bottom of this question), I observe a kind of "bounce" effect: As soon as the zoom operation ends, the zoomed content briefly moves to a different location, then immediately moves back to its original location.
I am not entirely sure what the reason for the "bounce" effect is: Either there are two GUI update cycles (one for resetting zoomScale to 1.0, and another for setNeedsDisplay), or some sort of animation is taking place that makes both changes visible, one after the other.
My question is: How can I prevent the "bounce" effect described above?
UPDATE: The following is a minimal but complete code example that you can simply copy&paste to observe the effect that I am talking about.
Create a new Xcode project using the "Empty application" template.
Add the code below to AppDelegate.h and AppDelegate.m, respectively.
In the project's Link build phase, add a reference to QuartzCore.framework.
Stuff that goes into AppDelegate.h:
#import <UIKit/UIKit.h>
#class LayerView;
#interface AppDelegate : UIResponder <UIApplicationDelegate, UIScrollViewDelegate>
#property (nonatomic, retain) UIWindow* window;
#property (nonatomic, retain) LayerView* layerView;
#end
Stuff that goes into AppDelegate.m:
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#class LayerDelegate;
#interface LayerView : UIView
#property (nonatomic, retain) LayerDelegate* layerDelegate;
#end
#interface LayerDelegate : NSObject
#property(nonatomic, retain) CALayer* layer;
#property (nonatomic, assign) CGFloat zoomScale;
#end
static CGFloat kMinimumZoomScale = 1.0;
static CGFloat kMaximumZoomScale = 5.0;
#implementation AppDelegate
- (void) dealloc
{
self.window = nil;
self.layerView = nil;
[super dealloc];
}
- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
[UIApplication sharedApplication].statusBarHidden = YES;
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.window.backgroundColor = [UIColor whiteColor];
UIScrollView* scrollView = [[[UIScrollView alloc] initWithFrame:self.window.bounds] autorelease];
[self.window addSubview:scrollView];
scrollView.contentSize = scrollView.bounds.size;
scrollView.delegate = self;
scrollView.minimumZoomScale = kMinimumZoomScale;
scrollView.maximumZoomScale = kMaximumZoomScale;
scrollView.zoomScale = 1.0f;
scrollView.bouncesZoom = NO;
self.layerView = [[[LayerView alloc] initWithFrame:scrollView.bounds] autorelease];
[scrollView addSubview:self.layerView];
[self.window makeKeyAndVisible];
return YES;
}
- (UIView*) viewForZoomingInScrollView:(UIScrollView*)scrollView
{
return self.layerView;
}
- (void) scrollViewDidEndZooming:(UIScrollView*)scrollView withView:(UIView*)view atScale:(float)scale
{
CGPoint contentOffset = scrollView.contentOffset;
CGSize contentSize = scrollView.contentSize;
scrollView.maximumZoomScale = scrollView.maximumZoomScale / scale;
scrollView.minimumZoomScale = scrollView.minimumZoomScale / scale;
// Big change here: This resets the scroll view's contentSize and
// contentOffset, and also the LayerView's frame, bounds and transform
// properties
scrollView.zoomScale = 1.0f;
CGFloat newZoomScale = self.layerView.layerDelegate.zoomScale * scale;
self.layerView.layerDelegate.zoomScale = newZoomScale;
self.layerView.frame = CGRectMake(0, 0, contentSize.width, contentSize.height);
scrollView.contentSize = contentSize;
[scrollView setContentOffset:contentOffset animated:NO];
[self.layerView setNeedsDisplay];
}
#end
#implementation LayerView
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.layerDelegate = [[[LayerDelegate alloc] init] autorelease];
[self.layer addSublayer:self.layerDelegate.layer];
// super's initWithFrame already invoked setNeedsDisplay, but we need to
// repeat because at that time our layerDelegate property was still empty
[self setNeedsDisplay];
}
return self;
}
- (void) dealloc
{
self.layerDelegate = nil;
[super dealloc];
}
- (void) setNeedsDisplay
{
[super setNeedsDisplay];
// Zooming changes the view's frame, but not the frame of the layer
self.layerDelegate.layer.frame = self.bounds;
[self.layerDelegate.layer setNeedsDisplay];
}
#end
#implementation LayerDelegate
- (id) init
{
self = [super init];
if (self)
{
self.layer = [CALayer layer];
self.layer.delegate = self;
self.zoomScale = 1.0f;
}
return self;
}
- (void) dealloc
{
self.layer = nil;
[super dealloc];
}
- (void) drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
CGRect layerRect = self.layer.bounds;
CGFloat radius = 25 * self.zoomScale;
CGFloat centerDistanceFromEdge = 5 * self.zoomScale + radius;
CGPoint topLeftCenter = CGPointMake(CGRectGetMinX(layerRect) + centerDistanceFromEdge,
CGRectGetMinY(layerRect) + centerDistanceFromEdge);
[self drawCircleWithCenter:topLeftCenter radius:radius fillColor:[UIColor redColor] inContext:context];
CGPoint layerCenter = CGPointMake(CGRectGetMidX(layerRect), CGRectGetMidY(layerRect));
[self drawCircleWithCenter:layerCenter radius:radius fillColor:[UIColor greenColor] inContext:context];
CGPoint bottomRightCenter = CGPointMake(CGRectGetMaxX(layerRect) - centerDistanceFromEdge,
CGRectGetMaxY(layerRect) - centerDistanceFromEdge);
[self drawCircleWithCenter:bottomRightCenter radius:radius fillColor:[UIColor blueColor] inContext:context];
}
- (void) drawCircleWithCenter:(CGPoint)center
radius:(CGFloat)radius
fillColor:(UIColor*)color
inContext:(CGContextRef)context
{
const int startRadius = [self radians:0];
const int endRadius = [self radians:360];
const int clockwise = 0;
CGContextAddArc(context, center.x, center.y, radius,
startRadius, endRadius, clockwise);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillPath(context);
}
- (double) radians:(double)degrees
{
return degrees * M_PI / 180;
}
#end
Based on your sample project, the key is that you're manipulating a CALayer directly. By default, setting CALayer properties, such as frame, cause animations. The suggestion to use [UIView setAnimationsEnabled:NO] was on the right track, but only affects UIView-based animations. If you do the CALayer equivalent, say in your setNeedsDisplay: method:
[CATransaction begin];
[CATransaction setDisableActions:YES];
self.layerDelegate.layer.frame = self.bounds;
[CATransaction commit];
It prevents the implicit frame-changing animation and looks right to me. You can also disable these implicit animations via a CALayerDelegate method in your LayerDelegate class:
- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event {
return (id)[NSNull null]; // NSNull means "don't do any implicit animations"
}
Original Suggestions:
Perhaps you are in an animation block without knowing it? Or, perhaps one of the methods you're calling is setting up an animation block? What if you [UIView setAnimationsEnabled:NO] before your code and re-enable them after?
If it's not an animation, then it's probably as you suspect; two view updates of some kind. (Perhaps one from the scroll view, and one from your code somehow?) Some runnable sample code would be great in that case.
(Out of curiosity, have you tried using CALayer's shouldRasterize and rasterizationScale rather than faking out the zoom level?)
In the X Code user interface builder there's a Bounce setting (it's under Scroll View).
I want help with my UIScrollView sample.
I created a simple program that scrolls and zooms the content (UIImageView). It works fine, except that the content frequently disappears to the right-bottom when I try zooming out. But since I set minimumZoomScale to 1.0f, it is actually not zooming out, only the content is jumping out of the view. And what is even more weird is that I cannot scroll up after this. Apparently content size is messed up as well.
The setup I have in my sample code is as in the figure below.
When I checked the status after (trying) zooming out, I found two wrong things.
_scrollView.contentSize is 480x360, which should not be smaller than 1000x1000
_scrollView.bounds jumped to the top somehow (i.e., _scrollView.bounds.origin.y is always 0)
To cope with the two items above, I added following code in my UIScrollViewDelegate and now it works fine.
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
if(scrollView == _scrollView && view == _contentView)
{
// Setting ivars for scrollViewDidZoom
_contentOffsetBeforeZoom = _scrollView.contentOffset;
_scrollViewBoundsBeforeZoom = _scrollView.bounds;
}
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
if(scrollView == _scrollView)
{
// If you zoom out, there are cases where ScrollView content size becomes smaller than original,
// even though minimum zoom scale = 1. In that case, it will mess with the contentOffset as well.
if(_scrollView.contentSize.width < CONTENT_WIDTH || _scrollView.contentSize.height < CONTENT_HEIGHT)
{
_scrollView.contentSize = CGSizeMake(CONTENT_WIDTH, CONTENT_HEIGHT);
_scrollView.contentOffset = _contentOffsetBeforeZoom;
}
// If you zoom out, there are cases where ScrollView bounds goes outsize of contentSize rectangle.
if(_scrollView.bounds.origin.x + _scrollView.bounds.size.width > _scrollView.contentSize.width ||
_scrollView.bounds.origin.y + _scrollView.bounds.size.height > _scrollView.contentSize.height)
{
_scrollView.bounds = _scrollViewBoundsBeforeZoom;
}
}
}
However, does it need to come down to this? This is a very simple sequence, and it is hard to believe that Apple requires us to put this kind of effort. So, my bet is I am missing something here...
Following is my original code. Please help me find what I am doing wrong (or missing something)!
#define CONTENT_WIDTH 1000
#define CONTENT_HEIGHT 1000
>>>> Snip >>>>
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
_scrollView.contentSize = CGSizeMake(CONTENT_WIDTH, CONTENT_HEIGHT);
_scrollView.backgroundColor = [UIColor blueColor];
_scrollView.maximumZoomScale = 8.0f;
_scrollView.minimumZoomScale = 1.0f;
_scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
_scrollView.scrollEnabled = YES;
_scrollView.delegate = self;
[self.view addSubview:_scrollView];
_contentView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sample.jpg"]]; // sample.jpg is 480x360
CGPoint center = (CGPoint){_scrollView.contentSize.width / 2, _scrollView.contentSize.height / 2};
_contentView.center = center;
[_scrollView addSubview:_contentView];
_scrollView.contentOffset = (CGPoint) {center.x - _scrollView.bounds.size.width / 2, center.y - _scrollView.bounds.size.height / 2};
}
- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView
{
if(scrollView == _scrollView)
{
return _contentView;
}
return nil;
}
I created a quick sample project and had the same issue you described using the code you pasted. I don't exactly know what the "proper" way to zoom is in iOS but I found this tutorial which says that you need to recenter your contentView after the scrollView has been zoomed. I would personally expect it to be automatically re-centered given that it is the view you're returning in the viewForZoomingInScrollView delegate method but apparently not.
- (void)centerScrollViewContents {
CGSize boundsSize = _scrollView.bounds.size;
CGRect contentsFrame = _contentView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
_contentView.frame = contentsFrame;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
// The scroll view has zoomed, so we need to re-center the contents
[self centerScrollViewContents];
}
The code above is not written by me but is simply copied from the tutorial. I think its pretty straightforward. Also, centring the contentView seems to be a lot more elegant then constantly changing the bounds and content size of the scrollview so give it a try.
If anyone is having an issue of bouncing when you zooming out resulting background to show, try removing bounces (Bounces Zoom) in Interface Builder.
I was able to fix this problem using the delegate answer that adjusted the rates after zoom... but then I remembered I was using auto-layout, and just adding constraints for centering horizontally and vertically (in addition to the constraints tying the image to each edge of the scroll view) solved the issue for me without using the delegate methods.
Olshansk answer in swift 5
func scrollViewDidZoom(_ scrollView: UIScrollView) {
centerScrollViewContents()
}
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size;
var contentsFrame = container.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0;
} else {
contentsFrame.origin.x = 0.0;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0;
} else {
contentsFrame.origin.y = 0.0;
}
container.frame = contentsFrame;
}