I want to create scrollView with pagecontrol programmatically. How can i do that?
#pragma mark -
#pragma mark loadGalleryView
-(void) loadGalleryView{
galleryArr = [memberDic objectForKey:#"arrKey"];
if ([galleryArr count]%5 != 0)
{
noOfPages = ([galleryArr count]/5)+1;
}
else
{
noOfPages = [galleryArr count]/5;
}
viewControllers = [[NSMutableArray alloc] init];
for (int i=0; i<noOfPages; i++)
{
[viewControllers addObject:[NSNull null]];
}
[galleryScrollView setPagingEnabled:TRUE];
[galleryScrollView setContentSize:CGSizeMake(self.view.frame.size.width* noOfPages,69.0f)];
[galleryScrollView setShowsHorizontalScrollIndicator:FALSE];
[galleryScrollView setShowsVerticalScrollIndicator:FALSE];
[galleryScrollView setScrollsToTop:FALSE];
[galleryScrollView setDelegate:self];
[pageControl setNumberOfPages:noOfPages];
[pageControl setCurrentPage:0];
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
//-----------------Load scroll View----------------------------------
-(void) loadScrollViewWithPage:(int) page{
if (page < 0)
{
return;
}
if (page >= noOfPages)
{
return;
}
GalleryViewController *givc = [viewControllers objectAtIndex:page];
if ((NSNull *)givc == [NSNull null])
{
givc = [[GalleryViewController alloc] initWithPageNumber:page];
givc.imageArr = [galleryArr retain];
[viewControllers replaceObjectAtIndex:page withObject:givc];
[givc release];
}
if (nil == givc.view.superview)
{
CGRect frame = self.view.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
givc.view.frame = frame;
[galleryScrollView addSubview:givc.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = galleryScrollView.frame.size.width;
int page = floor((galleryScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
isPageControlUsed = NO;
}
in gallary View Controller in .m file
- (void)viewDidLoad {
[super viewDidLoad];
float x = 7.0f;
for (int i = (pageNumber*5); i<(pageNumber+1)*5; i++)
{
if (i<[imageArr count])
{
NSString *url = [imageArr objectAtIndex:i];
MyImageView *imgView = [[MyImageView alloc] initWithFrame:CGRectMake(x, 7.5f, 55.0f, 55.0f)];
[imgView addImageFrom:url];
[self.view addSubview:imgView];
[imgView release];
x = x+62.5f;
}
}
}
-(id)initWithPageNumber:(int) page{
if (self = [super initWithNibName:#"GalleryViewController" bundle:nil])
{
pageNumber = page;
}
return self;
}
Related
My main motive is to create a screen just like the iPad image gallery. Images are coming from a server and can be in numbers like5 or 50 or 100. i have followed Ray Wenderlich's tutorial and gone through it step by step (http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content) but still facing the issue.
I have a main scroll view (the outer) in which I want to have these images, so that I can zoom in / out each image with scrolling (and paging) feature and also when I double tap the image it should zoom to 2x and and second time double it should return to normal.
For that I have an inner scroll view which will hold an UIImageview for each image. So that each image can zoom in / out. But when I load the image I can only see the first image and other images are not displayed. when I set background color of each scroll view and the image view too I got to know that problem is with them but I can't figure out what it is:
Where is the problem in my code, I have searched a lot on internet but could not figure out, and I have tried many other samples.
Below is my code
.h file
#import <UIKit/UIKit.h>
#interface SliderViewController : UIViewController<UIScrollViewDelegate,MFMailComposeViewControllerDelegate,UIPrintInteractionControllerDelegate,UIAlertViewDelegate,UIPopoverControllerDelegate,ButtonPressedDelegate>
{
NSMutableArray *thumbsArray;
int index;
int count;
UIView *containerView;
bool isEmpty;
NSString *firstName;
NSString *lastName;
NSMutableArray *annotatedThumbsArray;
}
#property(nonatomic,retain) NSMutableArray *thumbsArray;
#property(nonatomic, assign) int index;
#property(nonatomic, assign) int count;
#property(nonatomic,retain) NSString *firstName;
#property(nonatomic,retain) NSString *lastName;
#property(nonatomic,retain) NSMutableArray *annotatedThumbsArray;
#property(nonatomic,retain) UIPopoverController *popover_controller;
#property(nonatomic,retain) IBOutlet UIScrollView *scrollView;
#property(nonatomic,retain) IBOutlet UIPageControl *pageControl;
#end
.m file:
#import "SliderViewController.h"
#import "AppDelegate.h"
#define VIEW_FOR_ZOOM_TAG (10)
#interface SliderViewController ()
{
UITapGestureRecognizer *singleFingerTap;
CGRect rect;
}
#property (nonatomic, strong) NSMutableArray *pageImages;
#property (nonatomic, strong) NSMutableArray *pageViews;
- (void)loadVisiblePages;
- (void)loadPage:(NSInteger)page;
- (void)purgePage:(NSInteger)page;
#end
implementation SliderViewController
#synthesize pageImages,pageControl,libid,libname,thumbsArray,index,count,imageNameLabel,imageNameView,footerView,navBar,firstName,lastName,annotatedThumbsArray;
#synthesize drawingViewController,popover_controller;
#synthesize pageViews = _pageViews;
#synthesize scrollView = _scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - view cycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"THUMBSSSSS%#",thumbsArray);
pageImages = [[NSMutableArray alloc]init];
isEmpty = false;
self.scrollView.backgroundColor = [UIColor greenColor];
NSInteger pageCount = self.thumbsArray.count;
// Set up the page control
self.pageControl.currentPage = index;
self.pageControl.numberOfPages = pageCount;
// Set up the array to hold the views for each page
_pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i)
{
[_pageViews addObject:[NSNull null]];
}
self.navBar.topItem.title = [NSString stringWithFormat:#"%# %#",self.firstName,self.lastName];
singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(viewTapped:)];
[self.view addGestureRecognizer:singleFingerTap];
rect = CGRectZero;
}
- (void)centerScrollViewContents
{
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = [self.scrollView viewWithTag:202].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.scrollView viewWithTag:202].frame = contentsFrame;
}
-(void)setViewContents
{
// Set up the content size of the scroll view
CGSize pagesScrollViewSize = self.scrollView.frame.size;
self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.thumbsArray.count, pagesScrollViewSize.height);
[self.scrollView setContentOffset:CGPointMake(index*pagesScrollViewSize.width, 0.0f)];
self.scrollView.delegate = self;
self.navBar.topItem.title = [NSString stringWithFormat:#"%# %#",firstName,lastName];
// Load the initial set of pages that are on screen
[self loadVisiblePages];
[self centerScrollViewContents];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setViewContents];
[self performSelectorOnMainThread:#selector(showHeaderFooterViews) withObject:nil waitUntilDone:YES];
}
- (void)loadVisiblePages
{
// First, determine which page is currently visible
CGFloat pageWidth = self.scrollView.frame.size.width;
NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));
// Update the page control
self.pageControl.currentPage = page;
// Work out which pages you want to load
isEmpty = false;
NSInteger firstPage = page - 1;
NSInteger lastPage = page + 1;
// Purge anything before the first page
for (NSInteger i=0; i<firstPage; i++) {
[self purgePage:i];
}
for (NSInteger i=firstPage; i<=lastPage; i++) {
[self loadPage:i];
}
for (NSInteger i=lastPage+1; i<self.thumbsArray.count; i++) {
[self purgePage:i];
}
thumbnail *tempThumb = [[thumbnail alloc]init];
tempThumb = [thumbsArray objectAtIndex:page];
NSString *image_name = [[NSString alloc]initWithFormat:#"%#",tempThumb.name];
tempThumb = nil;
[self.imageNameLabel setText:[NSString stringWithFormat:#"%#(%d/%d)",image_name,pageControl.currentPage+1,pageControl.numberOfPages]];
}
-(void)purgePage:(NSInteger)page
{
if(page < 0 || page >= self.thumbsArray.count+self.annotatedThumbsArray.count)
{
// If it's outside the range of what you have to display, then do nothing
return;
}
// Remove a page from the scroll view and reset the container array
UIView *pageView = [_pageViews objectAtIndex:page];
if ((NSNull*)pageView != [NSNull null])
{
[pageView removeFromSuperview];
[_pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
- (void)loadPage:(NSInteger)page
{
#try
{
if (page < 0 || page >= self.thumbsArray.count)
{
// If it's outside the range of what we have to display, then do nothing
return;
}
// Load an individual page, first checking if you've already loaded it
UIView *pageView = [_pageViews objectAtIndex:page]; // page views holds
if ((NSNull*)pageView == [NSNull null] || isEmpty)
{
CGRect frame = self.scrollView.bounds;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
frame = CGRectInset(frame, 10.0f, 0.0f);
thumbnail *tempThumb = [[thumbnail alloc]init];
tempThumb = [thumbsArray objectAtIndex:page];
NSString *image_name = [[NSString alloc]initWithFormat:#"%#",tempThumb.name];
tempThumb = nil;
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentDir = [path objectAtIndex:0];
NSString *docsPath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:#"downloaded/%#",libid]];
UIImage *fullImage = [[UIImage alloc]init];
NSString *imagePath;
if(page<(thumbsArray.count-annotatedThumbsArray.count))
{
imagePath = [docsPath stringByAppendingPathComponent:image_name];
}
else
{
documentDir = [documentDir stringByAppendingPathComponent:libid];
imagePath = [documentDir stringByAppendingPathComponent:image_name];
}
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if(fileExists)
{
NSLog(#"file NAMEEEE: - %#",image_name);
fullImage = [UIImage imageWithContentsOfFile:imagePath];
}
else
{
NSLog(#"FILE NOT FOUND");
fullImage = [UIImage imageNamed:#"noimage.jpg"];
isEmpty = true;
}
UIImageView *newPageView = [[UIImageView alloc] initWithImage:fullImage];
[newPageView setUserInteractionEnabled:YES];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame = frame;
newPageView.backgroundColor = [UIColor blueColor];
newPageView.tag = VIEW_FOR_ZOOM_TAG;
// ******* add each image view into a scroll view so that it can be zoomed and also can be swiped
UIScrollView *pageScrollView = [[UIScrollView alloc] initWithFrame:frame];
pageScrollView.tag = 202;
pageScrollView.minimumZoomScale = 1.0f;
pageScrollView.maximumZoomScale = 2.0f;
pageScrollView.zoomScale = 1.0f;
// pageScrollView.contentSize = newPageView.bounds.size;
pageScrollView.delegate = self;
pageScrollView.showsHorizontalScrollIndicator = NO;
pageScrollView.showsVerticalScrollIndicator = NO;
pageScrollView.backgroundColor = [UIColor yellowColor];
[self.scrollView addSubview:pageScrollView];
[pageScrollView addSubview:newPageView];
[self.scrollView bringSubviewToFront:pageScrollView];
NSLog(#"frame --> %f", frame.origin.x);
NSLog(#"frame --> %f", newPageView.frame.origin.x);
NSLog(#"frame --> %f", pageScrollView.frame.origin.x);
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(viewDoubleTapped:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.numberOfTouchesRequired = 1;
[newPageView addGestureRecognizer:doubleTapRecognizer];
}
}
#catch (NSException *exception)
{
NSLog(#"crash in - loadPage = %#", exception);
}
#finally {
// NSLog(#"finally-");
}
}
#pragma mark - double tapped
-(void)viewDoubleTapped:(UITapGestureRecognizer*)recognizer
{
//TODO: code for 2x zooming in / out
}
#pragma mrak - view tapped
-(void) viewTapped:(UITapGestureRecognizer*)recognizer
{
if([self.footerView isHidden])
{
[self performSelectorOnMainThread:#selector(showHeaderFooterViews) withObject:nil waitUntilDone:YES];
}
}
- (void)showHeaderFooterViews
{
[self.imageNameView setHidden:NO];
[self.footerView setHidden:NO];
[self performSelector:#selector(hideHeaderFooterViews) withObject:nil afterDelay:5.0];
}
- (void)hideHeaderFooterViews
{
NSLog(#"hide header footer called ");
[self.imageNameView setHidden:YES];
[self.footerView setHidden:YES];
}
#pragma mark - back button (cross button ) pressed
- (IBAction)backButtonPressed:(id)sender
{
#try
{
AppDelegate* myAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
int l = [[[myAppDelegate window].rootViewController childViewControllers] count];// to access the previous controller
FolderViewController *parentVC = (FolderViewController *)((UITabBarController *)[[[myAppDelegate window].rootViewController childViewControllers] objectAtIndex:l-2]); // accessing FolderviewC
[parentVC loadThumbnails];
[self.view removeFromSuperview];
[self removeFromParentViewController];
}
#catch (NSException *exception) {
NSLog(#"crash in SliderVC: backButtonPressed - %#", exception);
}
#finally {
}
}
#pragma mark - scroll view delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Load the pages that are now on screen
[self loadVisiblePages];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
if(scrollView.tag == 202)
return [scrollView viewWithTag:VIEW_FOR_ZOOM_TAG];
return nil;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
NSLog(#"view zoomed");
[self centerScrollViewContents ];
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
NSLog(#"Beginning zooming");
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale{
NSLog(#"Zooming Did End");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)swipeRight:(id)sender
{
if (!((self.scrollView.contentOffset.x+self.scrollView.frame.size.width) >= self.scrollView.contentSize.width))
{
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x+self.scrollView.frame.size.width, self.scrollView.contentOffset.y)];
[self loadVisiblePages];
}
}
- (IBAction)swipeLeft:(id)sender
{
if (!((self.scrollView.contentOffset.x-self.scrollView.frame.size.width) < 0))
{
[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x-self.scrollView.frame.size.width, self.scrollView.contentOffset.y)];
[self loadVisiblePages];
}
}
NOTE: I have saved my images which I am getting from server in Documents directory and accessing back them from my loadPage: method (is this the right place to access these images?)
I have a StoryBoard. In that there is a UIViewController - on that I have put UIScrollView and UIPageControl. And on each page (say I have 3) I am trying to load a UIViewController (that shows different labels and table values).
Problem - I am able to load everything up but the label and table is not visible. Thou when I try to change the background color for each page - it does gets changed. I have researched various posts and code but nothing seems to work / show UIScrollView with StoryBoard (with UIViewController displaying labels and table).
I am thou able to do this with loading a separate XIB file but then the whole segue gets interrupted.
Please see my code below.
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
//ScrollView and PageControl
// Create view controllers placeholder array
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPages; i++)
{
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
// Set Scroll View
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * numberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
// Set Page Control
pageControl.numberOfPages = numberOfPages;
pageControl.currentPage = 0;
// Load the visible and next page
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
if (pageControlUsed)
{
// To know if scroll is valid - from Page Control
return;
}
// Changes Page Control indicator
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// Load the visible, previous and next pages
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pageControlUsed = NO;
}
- (void)loadScrollViewWithPage:(int)page
{
if (page < 0) return;
if (page >= numberOfPages) return;
// Load new Controller
ReportsDetailViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{
controller = [[ReportsDetailViewController alloc] init];
controller.pageNumber = [NSNumber numberWithInt:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
}
if (nil == controller.view.superview)
{
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
Try to create your ViewControllers like this:
YourViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"YourViewController"];
You can set the identifier of your view controller in the attribute inspector.
I had the same problem today and this did the trick for me.
I'm using pageControl in my application. View's are not changing on click on dots but on the either end's of pageControl, when i click view's are changing. I want them to change on clicks on dot. What to do? Is there any method i need to implement?
Here's the Code
#import "ScrollingViewController.h"
#implementation ScrollingViewController
#synthesize scrollView;
#synthesize pageControl;
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupPage];
pageControl =[[UIPageControl alloc] initWithFrame:CGRectMake(0,390,320,100)];
pageControl.userInteractionEnabled =YES;
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[self.pageControl setBackgroundColor:[UIColor blackColor]];
pageControl.enabled = TRUE;
[pageControl setHighlighted:YES];
[pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pageControl];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[scrollView release];
[pageControl release];
}
- (void)dealloc
{
[super dealloc];
}
- (void)setupPage
{
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,400)];
[scrollView setContentSize:CGSizeMake(1000, 800)];
//scrollView.contentSize = CGSizeMake(1000,800);
scrollView.scrollsToTop = NO;
[self.scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
CGFloat cx = 0;
for (; ; nimages++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (image == nil)
{
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = image.size.height;
rect.size.width = image.size.width;
rect.origin.x = ((scrollView.frame.size.width - image.size.width) / 2) + cx;
rect.origin.y = ((scrollView.frame.size.height - image.size.height) / 2);
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += scrollView.frame.size.width;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
scrollView.delegate = self;
[self.view addSubview:scrollView];
}
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
if (pageControlIsChangingPage)
{
return;
}
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
pageControlIsChangingPage = NO;
}
- (IBAction)changePage:(id)sender
{
/*
* Change the scroll view
*/
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageControl.currentPage;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
pageControlIsChangingPage = YES;
}
#end
Increase the width of the page control as much as possible. Even if you keep the width of page control short enough to as many dots that it cannot hold, it can show them. But fails to receive the action.
Use in ScrollView.m
#pragma mark -
#pragma mark loadGalleryView
-(void) loadGalleryView{
galleryArr = [memberDic objectForKey:#"arrKey"];
if ([galleryArr count]%5 != 0)
{
noOfPages = ([galleryArr count]/5)+1;
}
else
{
noOfPages = [galleryArr count]/5;
}
viewControllers = [[NSMutableArray alloc] init];
for (int i=0; i<noOfPages; i++)
{
[viewControllers addObject:[NSNull null]];
}
[galleryScrollView setPagingEnabled:TRUE];
[galleryScrollView setContentSize:CGSizeMake(self.view.frame.size.width* noOfPages,69.0f)];
[galleryScrollView setShowsHorizontalScrollIndicator:FALSE];
[galleryScrollView setShowsVerticalScrollIndicator:FALSE];
[galleryScrollView setScrollsToTop:FALSE];
[galleryScrollView setDelegate:self];
[pageControl setNumberOfPages:noOfPages];
[pageControl setCurrentPage:0];
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
//-----------------Load scroll View----------------------------------
-(void) loadScrollViewWithPage:(int) page{
if (page < 0)
{
return;
}
if (page >= noOfPages)
{
return;
}
GalleryViewController *givc = [viewControllers objectAtIndex:page];
if ((NSNull *)givc == [NSNull null])
{
givc = [[GalleryViewController alloc] initWithPageNumber:page];
givc.imageArr = [galleryArr retain];
[viewControllers replaceObjectAtIndex:page withObject:givc];
[givc release];
}
if (nil == givc.view.superview)
{
CGRect frame = self.view.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
givc.view.frame = frame;
[galleryScrollView addSubview:givc.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = galleryScrollView.frame.size.width;
int page = floor((galleryScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
isPageControlUsed = NO;
}
Use in GalleryView .m
- (void)viewDidLoad {
[super viewDidLoad];
float x = 7.0f;
for (int i = (pageNumber*5); i<(pageNumber+1)*5; i++)
{
if (i<[imageArr count])
{
NSString *url = [imageArr objectAtIndex:i];
MyImageView *imgView = [[MyImageView alloc] initWithFrame:CGRectMake(x, 7.5f, 55.0f, 55.0f)];
[imgView addImageFrom:url];
[self.view addSubview:imgView];
[imgView release];
x = x+62.5f;
}
}
}
-(id)initWithPageNumber:(int) page{
if (self = [super initWithNibName:#"GalleryViewController" bundle:nil])
{
pageNumber = page;
}
return self;
}
I have this page control code same from the apple sample. Here i have a subview (controller.view) which contains a ImageView. Now problem is with memory management. All works fine. But when i scroll 5-10 pages. RAM gets filled.
I tried to release the view+controller but did not find any proper place/way that work. I want to release the views which are not currently visible. (except current,previous & next view)
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;
PageControlExampleViewControl *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[PageControlExampleViewControl alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (pageControlUsed) {
return;
}
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
pageControlUsed = YES;
}
I tried for several hours the code of Deepmist. It did the job but I received memory warnings and my app crashed every 25-30 pages scrolled (I am using big images in the pages). In Instruments I noticed a very large use of memory: even if the unnecessary views were removed time by time from superview and the relative viewControllers were replaced with NSNulls, Instruments showed that real memory increased on every pagescroll of 4-5MB!
Searching on the web I found that this is a common problem. If you also have this problem, you should try the following checks:
1) in each view, be sure to use imageWithContentsOfFile instead of imageNamed. As documented imageNamed cache images and increase memory size.
2) in the Deepmist code, after:
[controller.view removeFromSuperview];
you also have to set to nil the view:
controller.view=nil;
This trick solved the memory consumption which now is stable for the only three views loaded (current, current-1 and current+1 to avoid flashing in the pagescroll).
Hope this helps!
I didn't test this but I imagine you could write a method that does the opposite of loading like so:
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;
PageControlExampleViewControl *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller != [NSNull null]) {
if (nil != controller.view.superview)
[controller.view removeFromSuperview];
[viewControllers replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
Then add some code to your didScroll method like so:
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
in loadScrollViewWithPage method, just before if (nil == controller.view.superview), cycle trough all views and remove them all except current -1, current and current + 1 but only if method was called with current index view. Also, don't forget to replace those view controllers in viewControllers array with NSNulls.
try this VSScrollview , it reuses its views like UITableview reuses its cell.
Ok, so I am trying to a pagescrollView with two views each with a different view controller so I can work on each different view. I got apple's sample code and it seems that they created a lot of different view "lazily as they said" how can this code be altered so that I can have the first page be one view controller and the second page be another view controller?
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// view controllers are created lazily
// in the meantime, load the array with placeholders which will be replaced on demand
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;
// replace the placeholder if necessary
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[MyViewController alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// update the scroll view to the appropriate page
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
pageControlUsed = YES;
}
Thanks if anyone knows how to do this.
To load the pages with different view controllers all you have to change is this segment of code
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{ controller = [[MyViewController alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
to initialize each view controller to the one you want instead of the same one each time, so the code would look something like
if(page==0)
{
MyViewControllerZero *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{ controller = [[MyViewControllerZero alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
}
if(page==1)
{
MyViewControllerOne *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{ controller = [[MyViewControllerOne alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
}
//and so on ...
This is the Correct Code!!!
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;
// replace the placeholder if necessary
if (page == 0){
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[MyViewController alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
}
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
if (page == 1){
PageOne *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[PageOne alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
}
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
// add the controller's view to the scroll view
}
}
THX For the first answewr she open my mind!!!