In my application having gallery functionality.For Scrolling image i used REPagedScrollView and i want to image zoom on pinch using 2 finger and also want zoom on double tap but i unable to to zoom image on double tap
please resolved my problem.
I tried by below code :
.h file
#interface ViewPhotoVC : UIViewController<UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
REPagedScrollView *scrollView;
UIScrollView *image_scroll;
int current_page;
BOOL is_FullScreen;
}
#property (strong,nonatomic) IBOutlet UIView *slider_view;
.m file
-(void)video_image_Gallery
{
scrollView = [[REPagedScrollView alloc] initWithFrame:self.slider_view.bounds];
scrollView.delegate=self;
// scrollView.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
// scrollView.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
current_page=0;
for(int i=0;i<[self.PhotoImgArr count];i++){
self.image_view = [[AsyncImageView alloc] initWithFrame:CGRectMake(0,0, self.slider_view.frame.size.width, self.slider_view.frame.size.height)];
// scrollView.frame=CGRectMake(0, 0, screenwidth, screenheight);
image_scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,screenwidth,screenheight)];
self.image_view.backgroundColor=[UIColor clearColor];
self.image_view.contentMode = UIViewContentModeScaleAspectFit;
self.image_view.clipsToBounds = true;
self.image_view.userInteractionEnabled = YES;
self.image_view.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin);
self.image_view.image = [UIImage imageNamed:#"no_image1.png"];
self.image_view.imageURL =[NSURL URLWithString:[self.PhotoImgArr objectAtIndex:i]];
self.image_view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:246.0/255.0 blue:241.0/255.0 alpha:1];
[image_scroll setDelegate:self];
[image_scroll setShowsHorizontalScrollIndicator:NO];
[image_scroll setShowsVerticalScrollIndicator:NO];
[image_scroll setMaximumZoomScale:8.0];
image_scroll.tag=i+1;
self.PlayVideoBtn.tag=i+1;
self.image_view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
image_scroll.contentSize = CGSizeMake(self.image_view.bounds.size.width-500, self.image_view.bounds.size.height-300);
image_scroll.decelerationRate = UIScrollViewDecelerationRateFast;
// [image_scroll setMinimumZoomScale:[image_scroll frame].size.width / [self.image_view frame].size.width];
[image_scroll setZoomScale:[image_scroll minimumZoomScale]];
[image_scroll addSubview:self.image_view];
[image_scroll addSubview:self.PlayVideoBtn];
[image_scroll addSubview:self.videoImg];
scrollView.tag=0;
// self.PlayVideoBtn.tag=0;
[scrollView addPage:image_scroll];
}
[self.slider_view addSubview:scrollView];
self.index_lbl.text = [NSString stringWithFormat:#"%d of %lu",(int)self.selected_index+1,(unsigned long)[self.PhotoImgArr count]];
[scrollView scrollToPageWithIndex:self.selected_index animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
if(scrollView1.tag ==0){
CGFloat pageWidth = scrollView1.frame.size.width;
current_page = floor((scrollView1.contentOffset.x - pageWidth / 2.0) / pageWidth) + 1;
self.index_lbl.text = [NSString stringWithFormat:#"%d of %lu",current_page+1,(unsigned long)[self.PhotoImgArr count]];
if(current_page+1==self.PhotoImgArr.count)
{
self.nextBtn.userInteractionEnabled=NO;
self.nextImg.image=[UIImage imageNamed:#"disable_next.png"];
}
else if(current_page==0)
{
self.prevBtn.userInteractionEnabled=NO;
self.prevImg.image=[UIImage imageNamed:#"disable_prev.png"];
}
else
{
self.nextBtn.userInteractionEnabled=YES;
self.prevBtn.userInteractionEnabled=YES;
self.nextImg.image=[UIImage imageNamed:#"next.png"];
self.prevImg.image=[UIImage imageNamed:#"prev.png"];
}
}
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView1 {
if([self.PhotoOrVideo isEqualToString:#"Photo"])
{
if([[scrollView1 viewWithTag:scrollView1.tag].subviews count]>0){
return [[scrollView1 viewWithTag:scrollView1.tag].subviews objectAtIndex:0];
}
}
return nil;
}
Please try the below code:
-(void)setScrollView:(UIScrollView *)scrollView
{
_scrollView=scrollView;
_scrollView.minimumZoomScale=0.2;
_scrollView.maximumZoomScale=3.0;
_scrollView.delegate=self;
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
[self.scrollView flashScrollIndicators];
}
Related
I am new to iPhone to iOS development. and I want a demo for zoom in and zoom out (symmetric zooming of image) a image within a scrollview in iOS.This is my code : in this code i have taken an image view within a scrollview(ZoomScrollView) and scrollview within a another Scrollview(scrollView_Gallery).Thanks in advance..
//ZoomGalleryViewController.m//
scrollView_Gallery.backgroundColor = [UIColor yellowColor];
scrollView_Gallery.delegate = self;
scrollView_Gallery.pagingEnabled = YES;
scrollView_Gallery.userInteractionEnabled = YES;
scrollView_Gallery.showsHorizontalScrollIndicator = NO;
scrollView_Gallery.showsVerticalScrollIndicator = NO;
[self.view addSubview:scrollView_Gallery];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
{
[scrollView_Gallery setContentSize:CGSizeMake(self.view.frame.size.width*[arrayUrl count],self.view.frame.size.height)];
}
else if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
{
[scrollView_Gallery setContentSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width*[arrayUrl count],[[UIScreen mainScreen] bounds].size.height)];
}
for (int i = 0; i < [arrayUrl count]; i++)
{
zoomScrollView = [[ZoomScrollView alloc]init];
zoomScrollView.backgroundColor = [UIColor redColor];
[zoomScrollView setContentSize:CGSizeMake(zoomScrollView.contentSize.width,zoomScrollView.frame.size.height)];
CGRect frame = scrollView_Gallery.frame;
frame.origin.x = (frame.size.width)* i;
frame.origin.y = 0;
zoomScrollView.frame = frame;
zoomScrollView.imageView.contentMode = UIViewContentModeScaleAspectFit;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[arrayUrl objectAtIndex:i]objectForKey:#"photopath"]]];
__weak UIImageView *weakImageView = zoomScrollView.imageView;
zoomScrollView.imageView.tag = i;
zoomScrollView.ZOOM_VIEW_TAG = zoomScrollView.imageView.tag;
[zoomScrollView.imageView setImageWithURLRequest:request
placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
NSLog(#"image=%f,imageheight=%f",image.size.width,image.size.height);
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
strongImageView.frame = CGRectMake(0,0,image.size.width*image.scale, image.size.height*image.scale);
strongImageView.center = scrollView_Gallery.center;
NSLog(#"image11 = %f, imageheight11 = %f",image.size.width*image.scale, image.size.height*image.scale);
NSLog(#"imageScale = %f",image.scale);
if (!strongImageView) return;
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
strongImageView.image = image;
}
completion:NULL];
//[scrollView_Gallery setContentOffset:CGPointMake(strongImageView.frame.size.width * (indexNumber+1), 0)];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
NSLog(#"Request failed with error: %#", error);
}];
[scrollView_Gallery addSubview:zoomScrollView];
[zoomScrollView setContentSize:CGSizeMake(zoomScrollView.contentSize.width,zoomScrollView.frame.size.height)];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
{
[scrollView_Gallery setContentOffset:CGPointMake(self.view.frame.size.width * (indexNumber), 0)];
}
else if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
{
[scrollView_Gallery setContentOffset:CGPointMake([[UIScreen mainScreen] bounds].size.width * (indexNumber), 0)];
}
// ZoomScrollView.h//
#import <UIKit/UIKit.h>
#interface MRZoomScrollView : UIScrollView <UIScrollViewDelegate>
{
UIImageView *imageView;
}
#property (nonatomic, retain) UIImageView *imageView;
#end
// MRZoomScrollView.m//
#import "MRZoomScrollView.h"
#define MRScreenWidth CGRectGetWidth([UIScreen mainScreen].applicationFrame)
#define MRScreenHeight CGRectGetHeight([UIScreen mainScreen].applicationFrame)
#interface MRZoomScrollView (Utility)
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;
#end
#implementation MRZoomScrollView
#synthesize imageView;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
self.frame = CGRectMake(0, 0, MRScreenWidth, MRScreenHeight);
[self initImageView];
}
return self;
}
- (void)initImageView
{
imageView = [[UIImageView alloc]init];
// The imageView can be zoomed largest size
imageView.frame = CGRectMake(0, 0, MRScreenWidth * 2.5, MRScreenHeight * 2.5);
imageView.userInteractionEnabled = YES;
[self addSubview:imageView];
[imageView release];
// Add gesture,double tap zoom imageView.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleDoubleTap:)];
[doubleTapGesture setNumberOfTapsRequired:2];
[imageView addGestureRecognizer:doubleTapGesture];
[doubleTapGesture release];
float minimumScale = self.frame.size.width / imageView.frame.size.width;
[self setMinimumZoomScale:minimumScale];
[self setZoomScale:minimumScale];
}
#pragma mark - Zoom methods
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
float newScale = self.zoomScale * 1.5;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]];
[self zoomToRect:zoomRect animated:YES];
}
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
CGRect zoomRect;
zoomRect.size.height = self.frame.size.height / scale;
zoomRect.size.width = self.frame.size.width / scale;
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
return zoomRect;
}
#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return imageView;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
[scrollView setZoomScale:scale animated:NO];
}
You can do it by using UIScrollView and enable enabledZoom ON.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
in viewDidLoad method paste this code
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.minimumZoomScale=0.5;
self.scrollView.maximumZoomScale=6.0;
self.scrollView.contentSize=CGSizeMake(1280, 960);
self.scrollView.delegate=self;
}
Look at this tutorial, it was helpful for me:
Assuming you have a property scrollView, try the following code in your view controller s viewDidLoad or viewWillAppear methods:
self.scrollView.minimumZoomScale=1.0;
self.scrollView.maximumZoomScale=2.0;
self.scrollView.contentSize=self.scrollView.frame.size;
self.scrollView.bounces=YES;
self.scrollView.delegate=self;
Let your view controller conform to the UIScrollViewDelegate protocol. And implement the delegate method :
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;// return the imageView inside the scrollview which has to be scaled.
}
I have a pickerview that is getting its information from a separate AFPickerView file. I'm getting the error "Implicit conversion of 'int' to 'UIColor*' is disallowed with ARC". Any suggestions on an easy fix for this?
Here is the code that it effects:
[visibleViews minusSet:recycledViews];
// add missing pages
for (int index = firstNeededViewIndex; index <= lastNeededViewIndex; index++)
{
if (![self isDisplayingViewForIndex:index])
{
UILabel *label = (UILabel *)[self dequeueRecycledView];
if (label == nil)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(_rowIndent, 0, self.frame.size.width - _rowIndent, 39.0)];
label.backgroundColor = [UIColor clearColor];
label.font = self.rowFont;
label.textColor = RGBACOLOR(0.0, 0.0, 0.0, 0.75);
}
[self configureView:label atIndex:index];
[contentView addSubview:label];
[visibleViews addObject:label];
}
}
}
Here is the full code:
#import "AFPickerView.h"
#implementation AFPickerView
#pragma mark - Synthesization
#synthesize dataSource;
#synthesize delegate;
#synthesize selectedRow = currentRow;
#synthesize rowFont = _rowFont;
#synthesize rowIndent = _rowIndent;
#pragma mark - Custom getters/setters
- (void)setSelectedRow:(int)selectedRow
{
if (selectedRow >= rowsCount)
return;
currentRow = selectedRow;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:NO];
}
- (void)setRowFont:(UIFont *)rowFont
{
_rowFont = rowFont;
for (UILabel *aLabel in visibleViews)
{
aLabel.font = _rowFont;
}
for (UILabel *aLabel in recycledViews)
{
aLabel.font = _rowFont;
}
}
- (void)setRowIndent:(CGFloat)rowIndent
{
_rowIndent = rowIndent;
for (UILabel *aLabel in visibleViews)
{
CGRect frame = aLabel.frame;
frame.origin.x = _rowIndent;
frame.size.width = self.frame.size.width - _rowIndent;
aLabel.frame = frame;
}
for (UILabel *aLabel in recycledViews)
{
CGRect frame = aLabel.frame;
frame.origin.x = _rowIndent;
frame.size.width = self.frame.size.width - _rowIndent;
aLabel.frame = frame;
}
}
#pragma mark - Initialization
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// setup
[self setup];
// backgound
UIImageView *bacground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pickerBackground.png"]];
[self addSubview:bacground];
// content
contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)];
contentView.showsHorizontalScrollIndicator = NO;
contentView.showsVerticalScrollIndicator = NO;
contentView.delegate = self;
[self addSubview:contentView];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(didTap:)];
[contentView addGestureRecognizer:tapRecognizer];
// shadows
UIImageView *shadows = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pickerShadows.png"]];
[self addSubview:shadows];
// glass
UIImage *glassImage = [UIImage imageNamed:#"pickerGlass.png"];
glassImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 76.0, glassImage.size.width, glassImage.size.height)];
glassImageView.image = glassImage;
[self addSubview:glassImageView];
}
return self;
}
- (void)setup
{
_rowFont = [UIFont boldSystemFontOfSize:24.0];
_rowIndent = 30.0;
currentRow = 0;
rowsCount = 0;
visibleViews = [[NSMutableSet alloc] init];
recycledViews = [[NSMutableSet alloc] init];
}
#pragma mark - Buisness
- (void)reloadData
{
// empry views
currentRow = 0;
rowsCount = 0;
for (UIView *aView in visibleViews)
[aView removeFromSuperview];
for (UIView *aView in recycledViews)
[aView removeFromSuperview];
visibleViews = [[NSMutableSet alloc] init];
recycledViews = [[NSMutableSet alloc] init];
rowsCount = [dataSource numberOfRowsInPickerView:self];
[contentView setContentOffset:CGPointMake(0.0, 0.0) animated:NO];
contentView.contentSize = CGSizeMake(contentView.frame.size.width, 39.0 * rowsCount + 4 * 39.0);
[self tileViews];
}
- (void)determineCurrentRow
{
CGFloat delta = contentView.contentOffset.y;
int position = round(delta / 39.0);
currentRow = position;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * position) animated:YES];
[delegate pickerView:self didSelectRow:currentRow];
}
- (void)didTap:(id)sender
{
UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer *)sender;
CGPoint point = [tapRecognizer locationInView:self];
int steps = floor(point.y / 39) - 2;
[self makeSteps:steps];
}
- (void)makeSteps:(int)steps
{
if (steps == 0 || steps > 2 || steps < -2)
return;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:NO];
int newRow = currentRow + steps;
if (newRow < 0 || newRow >= rowsCount)
{
if (steps == -2)
[self makeSteps:-1];
else if (steps == 2)
[self makeSteps:1];
return;
}
currentRow = currentRow + steps;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:YES];
[delegate pickerView:self didSelectRow:currentRow];
}
#pragma mark - recycle queue
- (UIView *)dequeueRecycledView
{
UIView *aView = [recycledViews anyObject];
if (aView)
[recycledViews removeObject:aView];
return aView;
}
- (BOOL)isDisplayingViewForIndex:(NSUInteger)index
{
BOOL foundPage = NO;
for (UIView *aView in visibleViews)
{
int viewIndex = aView.frame.origin.y / 39.0 - 2;
if (viewIndex == index)
{
foundPage = YES;
break;
}
}
return foundPage;
}
- (void)tileViews
{
// Calculate which pages are visible
CGRect visibleBounds = contentView.bounds;
int firstNeededViewIndex = floorf(CGRectGetMinY(visibleBounds) / 39.0) - 2;
int lastNeededViewIndex = floorf((CGRectGetMaxY(visibleBounds) / 39.0)) - 2;
firstNeededViewIndex = MAX(firstNeededViewIndex, 0);
lastNeededViewIndex = MIN(lastNeededViewIndex, rowsCount - 1);
// Recycle no-longer-visible pages
for (UIView *aView in visibleViews)
{
int viewIndex = aView.frame.origin.y / 39 - 2;
if (viewIndex < firstNeededViewIndex || viewIndex > lastNeededViewIndex)
{
[recycledViews addObject:aView];
[aView removeFromSuperview];
}
}
[visibleViews minusSet:recycledViews];
// add missing pages
for (int index = firstNeededViewIndex; index <= lastNeededViewIndex; index++)
{
if (![self isDisplayingViewForIndex:index])
{
UILabel *label = (UILabel *)[self dequeueRecycledView];
if (label == nil)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(_rowIndent, 0, self.frame.size.width - _rowIndent, 39.0)];
label.backgroundColor = [UIColor clearColor];
label.font = self.rowFont;
label.textColor = RGBACOLOR(0.0, 0.0, 0.0, 0.75);
}
[self configureView:label atIndex:index];
[contentView addSubview:label];
[visibleViews addObject:label];
}
}
}
- (void)configureView:(UIView *)view atIndex:(NSUInteger)index
{
UILabel *label = (UILabel *)view;
label.text = [dataSource pickerView:self titleForRow:index];
CGRect frame = label.frame;
frame.origin.y = 39.0 * index + 78.0;
label.frame = frame;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self tileViews];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
[self determineCurrentRow];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self determineCurrentRow];
}
#end
This should work with ARC. Replace RGBACOLOR with colorWithRed:green:blue:alpha
label.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.75f];
Hi my requirement is showing image in scrollview along with that it should display next and previous button.User can scroll the image as well as use buttons to move images.
I have doubt about how to get the index/tag/imagename or anything else when user scroll based on that values buttons should be updated.
Here is my Code
[self arrayInitiaisation];
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical = NO;
scrollview.alwaysBounceHorizontal = YES;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"image%d",i+1]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag = i;
...
Array Initialisation method
-(void) arrayInitialisation {
count=0;
[super viewDidLoad];
images=[NSMutableArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
Action Methods
- (IBAction)nextButton:(id)sender {}
- (IBAction)prevButton:(id)sender {}
scroll is working correctly but when user clicks on prev and next image is not updating on 'imageview'
Here is my updated code
int count=0;
- (void)viewDidLoad
{
[super viewDidLoad];
[self arrayInitialisation];
[scrollview setScrollEnabled:YES];
self.scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(30 , 30, 320, 412)];
self.scrollview.delegate=self;
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical=NO;
scrollview.alwaysBounceHorizontal=YES;
scrollview.showsHorizontalScrollIndicator=NO;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(xOrigin, 0, 320, 412)];
imageView.image = [images objectAtIndex:i];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag=i;
}
scrollview.contentSize = CGSizeMake(320*numberOfViews, 412);
scrollview.contentOffset = CGPointMake(0,0);
[self.view addSubview:self.scrollview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void) arrayInitialisation{
count=0;
[super viewDidLoad];
images=[NSArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
- (IBAction)nextButton:(id)sender {
if(count==0){
count++;
NSLog(#"Next Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
}
else{
[previous setEnabled:YES];
count++;
NSLog(#"Next Button : else Loop %d",count);
if(count <images.count){
[imageView setImage:[images objectAtIndex:count]];
}
else{
[next setEnabled:NO];
}
}
}
- (IBAction)prevButton:(id)sender {
if(count==0){
//count--;
NSLog(#"prev Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:NO];
[next setEnabled:YES];
}
else{
count--;
NSLog(#"prev Button : else Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
//[next setEnabled:YES];
}
}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate: (BOOL)decelerate{
//NSLog(#"scrollViewDidEndDragging");
/* count=count+1;
NSLog(#"scrollViewDidEndDragging : %d",count);*/
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//NSLog(#"scrollViewDidScroll");
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0){
//NSLog(#"scrollViewWillEndDragging");
count=count+1;
NSLog(#"scrollViewWillEndDragging : %d",count);
}
I have left and right button for scroll images, and imageview width is same.
I am writing code for scroll image at pressing button.
int pos=0;// ViewDiaLoad
- (IBAction)OnClickLeftButton:(UIButton*)sender
{
if(pos>0)
{
pos -=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
- (IBAction)OnClickRightButton:(UIButton*)sender
{
if(pos<numberOfImages)
{
pos +=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
Set scrollView Deleagte
Scroll View delegate Method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pos=scrollView.contentOffset.x/scrollView.frame.size.width;
}
You can use UIPageControl and set and get image according to page index. For more information check out this link
Try below piece of code. I hope it will help. Put this in your .h file
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
NSMutableArray *arrImages;
NSInteger page;
Now in your - (void)viewDidLoad put following lines.
int x = 30;
for (int i=0; i< arrImages.count; i++)
{
UIImageView *imgShow = [[UIImageView alloc]initWithFrame:CGRectMake(x+20, 50, self.view.frame.size.width-100, self.view.frame.size.height-180)];
imgShow.backgroundColor = [UIColor whiteColor];
imgShow.image = [UIImage imageNamed:[arrImages objectAtIndex:i]];
imgShow.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview:imgShow];
x = x+scrollView.frame.size.width;
}
scrollView.contentSize = CGSizeMake(5*self.view.frame.size.width, 0);
pageControl.backgroundColor = [UIColor clearColor];
pageControl.pageIndicatorTintColor = [UIColor grayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
[pageControl setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];
pageControl.numberOfPages = arrTitle.count;
pageControl.currentPage = 0;
implement scroll view delegate.
#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
CGFloat pageWidth = scrollView.frame.size.width;
float fractionalPage = scrollView.contentOffset.x / pageWidth;
page = lround(fractionalPage);
pageControl.currentPage = page;
}
- (IBAction)prevButton:(UIButton *)sender
{
page = page-1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
- (IBAction)nextButton:(UIButton *)sender
{
page = page+1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
I have two Scroll View's in a xib, and they both contain a very large image that should start with it completely scaled down to fit. The first ScrollView works perfectly, objects are all moving around correctly when you zoom or scroll, but the second ScrollView starts completely zoomed in, unable to zoom out.
The ScrollView is now showing 25% of the image(completely zoomed in at 0,0) and also cannot be dragged to see the rest. If I pinch to zoom, the image moves diagonally up and left without zooming at all, I can now drag the image back to 0,0 and back down the the max point it scrolled diagonally.
.h file
UIScrollView *_scrollView;
UIScrollView *_miamiScrollView;
UIView *_mapImageView;
UIView *_mapMiamiView;
UIView *_mapContentView;
NSArray *_autoLayoutViews;
NSArray *_staticViews;
#property (strong, nonatomic) IBOutlet UIScrollView *scrollView;//(linked to working scrollview)
#property (strong, nonatomic) IBOutlet UIScrollView *miamiScrollView;//(Linked to 'broken' scrollview)
.m file
- (void)viewDidLoad
{
[self _customizeViews];
}
- (void) _customizeViews
{
UIImageView *mapImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"MainGameDisplay.jpg"]];
mapImageView.userInteractionEnabled = YES;
UIImageView *mapMiamiView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"miami.jpg"]];
mapMiamiView.userInteractionEnabled = YES;
_mapContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, 568, 270)];
_mapContentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_mapContentView.clipsToBounds = YES;
_mapContentView.userInteractionEnabled = YES;
[_mapContentView addSubview:_scrollView];
[_mapContentView addSubview:_miamiScrollView];
[self.view addSubview:_mapContentView];
[self.view sendSubviewToBack:_mapContentView];
UIScrollView *scrollView = _scrollView;
CGRect scrollFrame = scrollView.frame;
scrollFrame.origin = CGPointZero;
scrollView.frame = scrollFrame;
scrollView.delegate = self;
scrollView.minimumZoomScale = 1;
scrollView.maximumZoomScale = 1.0;
[scrollView addSubview:mapImageView];
scrollView.contentSize = mapImageView.frame.size;
_scrollView = scrollView;
_mapImageView = mapImageView;
UIScrollView *miamiScrollView = _miamiScrollView;
CGRect miamiScrollFrame = CGRectMake(0 , 270, 568, 270);
scrollFrame.origin = CGPointZero;
miamiScrollView.frame = miamiScrollFrame;
miamiScrollView.delegate = self;
miamiScrollView.minimumZoomScale = 0.125;
miamiScrollView.maximumZoomScale = 1;
[miamiScrollView addSubview:mapMiamiView];
miamiScrollView.contentSize = mapMiamiView.frame.size;
_miamiScrollView = miamiScrollView;
_mapMiamiView = mapMiamiView;
[self _setupAutolayoutViews];
[self _setupStaticViews];
[self _zoomToFit: _scrollView];
[self _zoomToFit: _miamiScrollView];
[self _updatePositionForViews:_autoLayoutViews];
}
- (void) _zoomToFit: (UIScrollView*)view
{
CGFloat contentWidth = view.contentSize.width;
CGFloat contentHeigth = view.contentSize.height;
CGFloat viewWidth = view.frame.size.width;
CGFloat viewHeight = view.frame.size.height;
CGFloat width = viewWidth / contentWidth;
CGFloat heigth = viewHeight / contentHeigth;
CGFloat scale = MAX(width, heigth);
if ( scale < view.minimumZoomScale ) {
view.minimumZoomScale = scale;
} else if ( scale > view.maximumZoomScale ) {
view.maximumZoomScale = scale;
}
view.zoomScale = scale;
}
#pragma mark - Positions
- (void) _updatePositionForViews:(NSArray *)views
{
CGFloat scale = _scrollView.zoomScale;
CGPoint contentOffset = _scrollView.contentOffset;
contentOffset.x -= _scrollView.frame.origin.x;
contentOffset.y -= _scrollView.frame.origin.y;
for ( UIView *view in views ) {
CGPoint basePosition = [self _basePositionForView:view];
[self _updatePositionForView:view scale:scale basePosition:basePosition offset:contentOffset];
}
}
- (CGPoint) _basePositionForView:(UIView *)view
{
NSString *key = [NSString stringWithFormat:#"%d", view.tag];
NSString *stringValue = [_coordinates objectForKey:key];
NSArray *values = [stringValue componentsSeparatedByString:#":"];
if ( [values count] < 2 ) return CGPointZero;
CGPoint result = CGPointMake([[values objectAtIndex:0] floatValue], [[values objectAtIndex:1] floatValue]);
return result;
}
- (void) _updatePositionForView:(UIView *)view scale:(CGFloat)scale basePosition:(CGPoint)basePosition offset:(CGPoint)offset;
{
CGPoint position;
position.x = (basePosition.x * scale) - offset.x;
position.y = (basePosition.y * scale) - offset.y;
CGRect frame = view.frame;
frame.origin = position;
view.frame = frame;
}
//////////////////////////////////////////////////////////////////////////////////////
#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
{
[self _lockInteraction];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
[self _unlockInteraction];
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
[self _lockInteraction];
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;
{
[self _unlockInteraction];
}
- (void) _lockInteraction
{
[self _setControls:_staticViews interacted:NO];
[self _setControls:_autoLayoutViews interacted:NO];
}
- (void) _unlockInteraction
{
[self _setControls:_staticViews interacted:YES];
[self _setControls:_autoLayoutViews interacted:YES];
}
- (void) _setControls:(NSArray *)controls interacted:(BOOL)interacted
{
for ( UIControl *control in controls ) {
if ( [control isKindOfClass:[UIControl class]]) {
control.userInteractionEnabled = interacted;
}
}
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
[self _updatePositionForViews:_autoLayoutViews];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self _updatePositionForViews:_autoLayoutViews];
}
- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView;
{
return _mapImageView;
}
//DEFAULT BUTTONS.
- (void) _setupAutolayoutViews
{
UIButton *btn1 = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
[btn1 addTarget:self action:#selector(quickTest:) forControlEvents:UIControlEventTouchUpInside];
btn1.tag = kAddContactButton;
btn1.center = CGPointZero;
[_mapContentView addSubview:btn1];
_autoLayoutViews = [[NSArray alloc] initWithObjects:btn1, nil];
}
//CUSTOM BUTTONS.
- (void) _setupStaticViews
{
UIButton *openMiamiButton = [UIButton buttonWithType:UIButtonTypeCustom];
[openMiamiButton setBackgroundImage:[UIImage imageNamed:#"logo.png"] forState:UIControlStateNormal];
[openMiamiButton addTarget:self action:#selector(quickTest:) forControlEvents:UIControlEventTouchUpInside];
openMiamiButton.frame = CGRectMake(0.0 ,0.0, 50.0, 50.0);
openMiamiButton.tag = OpenMiamiButton;
openMiamiButton.enabled = YES;
openMiamiButton.alpha = 0.5;
[_mapImageView addSubview:openMiamiButton];
_staticViews = #[openMiamiButton,];
for ( UIView *view in _staticViews ) {
CGPoint point = [self _basePositionForView:view];
CGRect frame = view.frame;
frame.origin = point;
view.frame = frame;
}
}
//And for the transition between views:
-(void) quickTest: (UIButton *)button
{
/*
if (!openMiami)
openMiami = [[MiamiGameDisplay alloc] initWithNibName:nil bundle:nil];
openMiami.mainPage = self;
[self.navigationController pushViewController:openMiami animated:YES];
*/
if (!testBool){
[UIView animateWithDuration:0.5f
animations:^{
_scrollView.frame = CGRectMake(0 , -270, 568, 270);
}
completion:Nil];
[UIView animateWithDuration:0.5f
animations:^{
_miamiScrollView.frame = CGRectMake(0 , 0, 568, 270);
}
completion:Nil];
testBool=YES;
}
else {
[UIView animateWithDuration:0.5f
animations:^{
_miamiScrollView.frame = CGRectMake(0 , 270, 568, 270);
}
completion:Nil];
[UIView animateWithDuration:0.5f
animations:^{
_scrollView.frame = CGRectMake(0 , 0, 568, 270);
}
completion:Nil];
testBool=NO;
}
}
I've run into a similar issue with scrollViews. Basically, as far as I can tell, only the last scrollView added to the window will respond as a scrollView.
You can produce the same effect with any other type of object being added to the window before the scrollView.
Example :
[[self window] addSubview:logo];
[[self window] addSubview:scrollView];
Will work, but:
[[self window] addSubview:scrollView];
[[self window] addSubview:logo];
will not. (Currently running against iOS 6.1.2 and xCode 4.6.1)
I have a UIScrollView that loads three different pages.When i zoom in on a page, and zoom back out to the original size, the application stops letting me scroll between the pages, as if paging is disabled. What can i do to re-enable paging when zoomed out to the original size (Scale == 1)?
This is my code
- (void)viewDidLoad
{
[ScView setMaximumZoomScale : 2.0f];
[ScView setMinimumZoomScale : 1.0f];
ScView.contentSize = CGSizeMake(1024*3, 1.0);
ScView.pagingEnabled = YES;
ScView.clipsToBounds = YES;
ScView.delegate = self;
ScView.showsHorizontalScrollIndicator = NO;
ScView.showsVerticalScrollIndicator = NO;
[super viewDidLoad];
[self returnImages];
}
-(void)returnImages{
for (pageNumber = 1; pageNumber <= 3; pageNumber++) {
imagen = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"%d.png",pageNumber]]];
imagen.frame = CGRectMake((pageNumber-1)*1024, 0, 1024, 768);
[ScView addSubview:imagen];
}
}
//
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return ScView;
// return [imagen initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"%d.png",pageNumber]]];
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)myScrollView withView:(UIView *)view
{
NSLog(#"Scroll Will Begin");
ScView.scrollEnabled = YES;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)myScrollView withView:(UIView *)view atScale:(float)scale
{
if(scale == 1)
{
ScView.scrollEnabled = YES;
ScView.pagingEnabled = YES;
[self returnImages];
NSLog(#"Scrolol will end");
//ScView.maximumZoomScale = 2.0f;
// [super viewDidLoad];
[self returnImages];
}
}
Any ideas will be highly appreciated..
To get proper paging and zooming you have to embed UIScrollView for each page into your parent UIScrollView. This combination will allow you to use simultaneously paging and internal scrolling.
Here is the example of UIViewController with parent scroll view and three embedded zoomable pages.
#define VIEW_FOR_ZOOM_TAG (1)
#implementation SVViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
mainScrollView.pagingEnabled = YES;
mainScrollView.showsHorizontalScrollIndicator = NO;
mainScrollView.showsVerticalScrollIndicator = NO;
CGRect innerScrollFrame = mainScrollView.bounds;
for (NSInteger i = 0; i < 3; i++) {
UIImageView *imageForZooming = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"page%d", i + 1]]];
imageForZooming.tag = VIEW_FOR_ZOOM_TAG;
UIScrollView *pageScrollView = [[UIScrollView alloc] initWithFrame:innerScrollFrame];
pageScrollView.minimumZoomScale = 1.0f;
pageScrollView.maximumZoomScale = 2.0f;
pageScrollView.zoomScale = 1.0f;
pageScrollView.contentSize = imageForZooming.bounds.size;
pageScrollView.delegate = self;
pageScrollView.showsHorizontalScrollIndicator = NO;
pageScrollView.showsVerticalScrollIndicator = NO;
[pageScrollView addSubview:imageForZooming];
[mainScrollView addSubview:pageScrollView];
if (i < 2) {
innerScrollFrame.origin.x += innerScrollFrame.size.width;
}
}
mainScrollView.contentSize = CGSizeMake(innerScrollFrame.origin.x + innerScrollFrame.size.width, mainScrollView.bounds.size.height);
[self.view addSubview:mainScrollView];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [scrollView viewWithTag:VIEW_FOR_ZOOM_TAG];
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate {
return NO;
}
#end
I follow #NikNarmo 's solution, write a small swift xcode project to demo the zooming and paging function.
Hope to help anyone who want to do the same task.
Some code is from UIScrollView Tutorial: Getting Started http://www.raywenderlich.com/76436/use-uiscrollview-scroll-zoom-content-swift,
and some from A Beginner’s Guide to UIScrollView http://www.appcoda.com/uiscrollview-introduction/.
Using Xcode 7.0 and Swift 2.0
override func viewDidLoad() {
super.viewDidLoad()
mainScrollView = UIScrollView(frame: self.view.bounds)
mainScrollView.pagingEnabled = true
mainScrollView.showsHorizontalScrollIndicator = false
mainScrollView.showsVerticalScrollIndicator = false
pageScrollViews = [UIScrollView?](count: photos.count, repeatedValue: nil)
let innerScrollFrame = mainScrollView.bounds
mainScrollView.contentSize =
CGSizeMake(innerScrollFrame.origin.x + innerScrollFrame.size.width,
mainScrollView.bounds.size.height)
mainScrollView.backgroundColor = UIColor.redColor()
mainScrollView.delegate = self
self.view.addSubview(mainScrollView)
configScrollView()
addPageControlOnScrollView()
}
and the magic is in the func scrollViewWillEndDragging, when the contentSize is equal to the mainScrollViewContentSize or not, if it is mainScrollViewController, then do paging, otherwise do nothing.
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset = targetContentOffset.memory.x
let zoomRatio = scrollView.contentSize.height / mainScrollViewContentSize.height
if zoomRatio == 1 {
// mainScrollViewController
let mainScrollViewWidthPerPage = mainScrollViewContentSize.width / CGFloat(pageControl.numberOfPages)
let currentPage = targetOffset / (mainScrollViewWidthPerPage * zoomRatio)
pageControl.currentPage = Int(currentPage)
loadVisiblePages()
}
else {
// pageScorllViewController
}
}
And here is the project code https://github.com/Charles-Hsu/ScrollViewDemo