0
votes

I am trying to use UIScrollview and UIImageview to zoom an image...the UIscrollview is 300 by 300 and positioned at center of storyboard..it works however...when view loads the image takes position on the top left corner(not exactly either) of the scrollview..but I want it to be at the center of the scrollview when the view loads...can anyone suggest anything??

#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UIScrollView *scrollview;
@property (strong,nonatomic) UIImageView *imageview;

@end

@implementation ViewController
@synthesize scrollview,imageview;


-(void)viewDidLoad {
[super viewDidLoad];


scrollview.delegate=self;

UIImage *image = [UIImage imageNamed:@"back.jpg"];
imageview = [[UIImageView alloc] initWithImage:image];

imageview.contentMode=UIViewContentModeCenter;
imageview.frame=CGRectMake(0,0,scrollview.frame.size.width,scrollview.frame.size.height);
imageview.userInteractionEnabled=YES;
[scrollview addSubview:imageview];
scrollview.contentSize=image.size;

}

-(void)viewWillAppear:(BOOL)animated{


CGRect scrollviewframe=scrollview.frame;
CGFloat scaleWidth=scrollviewframe.size.width/scrollview.contentSize.width;
CGFloat scaleHeight=scrollviewframe.size.height/scrollview.contentSize.height;
CGFloat scaleMin= MIN(scaleWidth, scaleHeight);
scrollview.minimumZoomScale=scaleMin;
scrollview.maximumZoomScale=1;
scrollview.zoomScale=scaleMin;
[self centerScrollviewContents];

}
2

2 Answers

2
votes

I'd suggest to use Auto Layout in your Storyboard. Setting the leading space, top space, trailing space and bottom space between the UIImageView and UIScrollView to 0 (or a positive integer in case of padding) should do the trick.

1
votes

The UIScrollView is initialized with a default value: contentOffset = CGPointZero.
You need to calculate the appropriate offset and set it by code.

The image should be in the top left corner of the scrollView, the contentSize is determined by the size of the image to allow scrolling.