Top of the page
Close

This is a red error

This is a red error

This is a red error

How to build UIScrollView with page control

Ondrej Rafaj on 2010.04.12 18:07:58

Few days ago I needed to build horizontal UIScrollView with pagination, then I started thinking about reusing the code later and this is the result. I started Google Code project, it is a static library that is so far handling different types of UIScrollView but we are working on it every day, than stay tuned cause there will be much more to come :)

Today, I'll show you one of the classes I've built for this project, this library will help you to build and display horizontal UIScrollView with unlimited images that you can supply from an array that contains your UIImages.

First of all these are the files you have to include into your project if you are not using the entire static library that can be found here:

http://code.google.com/p/iphone-guru-uilibrary/

Header file:

///
///  IGUIScrollViewImage.h
///
///  IGUILibrary
///
///  Created by Ondrej Rafaj on 7.4.10.
///
///  Copyright 2010 Home. All rights reserved.
///
/// 


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>


@interface IGUIScrollViewImage : NSObject <UIScrollViewDelegate> {
	
	UIScrollView *scrollView;
	UIPageControl *pageControl;
	
	CGRect rectScrollView;
	CGRect rectPageControl;
	
	int scrollWidth;
	int scrollHeight;
	
	NSArray *contentArray;
	
	UIColor *bcgColor;
	
	BOOL pageControlEnabledTop;
	BOOL pageControlEnabledBottom;
	
	BOOL rememberPosition;
	NSString *positionIdentifier;
	
}

@property (nonatomic, retain) UIScrollView *scrollView;

/// returns width of the scollview
- (int)getScrollViewWidth;

/// set width and height for your final UIScrollView
- (void)setWidth:(int)width andHeight:(int)height;

/// set the exactly same size as it is your parent view
- (void)setSizeFromParentView:(UIScrollView *)scView;

/// set background color for your UIScrollView
- (void)setBackGroudColor:(UIColor *)color;

/// set an array with images you want to display in your new scroll view
- (void)setContentArray:(NSArray *)images;

/// display page control for the scroll view on the top of the view (inset)
- (void)enablePageControlOnTop;

/// display page control for the scroll view on the bottom of the view (inset)
- (void)enablePageControlOnBottom;

/// enable position history
- (void)enablePositionMemory;

/// enable position history with custom memory identifier
- (void)enablePositionMemoryWithIdentifier:(NSString *)identifier;

/// returns your UIScrollView with predefined page
- (UIScrollView *)getWithPosition:(int)page;

/// returns your UIScrollView with enabled position history
- (UIScrollView *)getWithPositionMemory;

/// returns your UIScrollView with enabled position history with custom memory identifier
- (UIScrollView *)getWithPositionMemoryIdentifier:(NSString *)identifier;

/// returns your UIScrollView
- (UIScrollView *)get;

@end

Implementation file:

//
//  IGUIScrollViewImage.m
//  IGUILibrary
//
//  Created by Ondrej Rafaj on 7.4.10.
//  Copyright 2010 Home. All rights reserved.
//

#import "IGUIScrollViewImage.h"

#define kIGUIScrollViewImagePageIdentifier						@"kIGUIScrollViewImagePageIdentifier"
#define kIGUIScrollViewImageDefaultPageIdentifier				@"Default"


@implementation IGUIScrollViewImage

@synthesize scrollView;

- (int)getScrollViewWidth {
	return ([contentArray count] * scrollWidth);
}

- (void)setWidth:(int)width andHeight:(int)height {
	scrollWidth = width;
	scrollHeight = height;
	if (!width || !height) rectScrollView = [[UIScreen mainScreen] applicationFrame];
	else rectScrollView = CGRectMake(0, 0, width, height);
}

- (void)setSizeFromParentView:(UIScrollView *)scView {
	scrollWidth = scView.frame.size.width;
	scrollHeight = scView.frame.size.height;
	rectScrollView = CGRectMake(0, 0, scrollWidth, scrollHeight);
}

- (void)setContentArray:(NSArray *)images {
	contentArray = images;
}

- (void)setBackGroudColor:(UIColor *)color {
	bcgColor = color;
}

- (void)enablePageControlOnTop {
	pageControlEnabledTop = YES;
}

- (void)enablePageControlOnBottom {
	pageControlEnabledBottom = YES;
}

- (void)enablePositionMemoryWithIdentifier:(NSString *)identifier {
	rememberPosition = YES;
	if (!identifier) identifier = kIGUIScrollViewImageDefaultPageIdentifier;
	positionIdentifier = identifier;
}

- (void)enablePositionMemory {
	[self enablePositionMemoryWithIdentifier:nil];
}

- (UIScrollView *)getWithPosition:(int)page {
	if (!contentArray) {
		contentArray = [[[NSArray alloc] init] autorelease];
	}
	if (page > [contentArray count]) page = 0;
	
	if (!scrollWidth || !scrollHeight) {
		rectScrollView = [[UIScreen mainScreen] applicationFrame];
		scrollWidth = rectScrollView.size.width;
		scrollHeight = rectScrollView.size.height;
	}
	rectScrollView = CGRectMake(0, 0, scrollWidth, scrollHeight);
	 
	self.scrollView = [[UIScrollView alloc] initWithFrame:rectScrollView];
    self.scrollView.contentSize = CGSizeMake([self getScrollViewWidth], scrollHeight);
	if (!bcgColor) bcgColor = [UIColor blackColor];
	self.scrollView.backgroundColor = bcgColor;
	self.scrollView.alwaysBounceHorizontal = YES;
	self.scrollView.contentOffset = CGPointMake(page * scrollWidth, 0);
	self.scrollView.pagingEnabled = YES;
	
	UIView *main = [[[UIView alloc] initWithFrame:rectScrollView] autorelease];
	int i = 0;
	for (UIImage *img in contentArray) {
		UIImageView *imageView = [[UIImageView alloc] init];
		imageView.image = img;
		imageView.contentMode = UIViewContentModeScaleAspectFit;
		imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
		imageView.backgroundColor = [UIColor blackColor];
		float ratio = img.size.width/rectScrollView.size.width;
		CGRect imageFrame = CGRectMake(i, 0, rectScrollView.size.width, (img.size.height / ratio));
		imageView.frame = imageFrame;
		[self.scrollView addSubview:(UIView *)imageView];
		i += scrollWidth;
		[imageView release];
	}
	[main addSubview:scrollView];
	if (pageControlEnabledTop) {
		rectPageControl = CGRectMake(0, 5, scrollWidth, 15);
	}
	else if (pageControlEnabledBottom) {
		rectPageControl = CGRectMake(0, (scrollHeight - 25), scrollWidth, 15);
	}
	if (pageControlEnabledTop || pageControlEnabledBottom) {
		pageControl = [[[UIPageControl alloc] initWithFrame:rectPageControl] autorelease];
		pageControl.numberOfPages = [contentArray count];
		pageControl.currentPage = page;
		[main addSubview:pageControl];
	}
	if (pageControlEnabledTop || pageControlEnabledBottom || rememberPosition) self.scrollView.delegate = self;
	//if (margin) [margin release];
	return (UIScrollView *)main;
}

- (UIScrollView *)get {
	return [self getWithPosition:0];
}

- (UIScrollView *)getWithPositionMemory {
	[self enablePositionMemory];
	return [self getWithPosition:[[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", kIGUIScrollViewImagePageIdentifier, kIGUIScrollViewImageDefaultPageIdentifier]] intValue]];
}

- (UIScrollView *)getWithPositionMemoryIdentifier:(NSString *)identifier {
	[self enablePositionMemoryWithIdentifier:identifier];
	return [self getWithPosition:[[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", kIGUIScrollViewImagePageIdentifier, positionIdentifier]] intValue]];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sv {
	int page = sv.contentOffset.x / sv.frame.size.width;
	pageControl.currentPage = page;
	if (rememberPosition) {
		[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d", page] forKey:[NSString stringWithFormat:@"%@%@", kIGUIScrollViewImagePageIdentifier, positionIdentifier]];
		[[NSUserDefaults standardUserDefaults] synchronize];
	}
}

- (void)dealloc {
	[scrollView release];
	[super dealloc];
}


@end

And now just a short example of how to use this class (of course you have to have all those images listed below in your application bundle):

- (NSArray *)getImages {
        NSMutableArray *arr = [[[NSMutableArray alloc] init] autorelease];
        [arr addObject:[UIImage imageNamed:@"1.jpg"]];
        [arr addObject:[UIImage imageNamed:@"2.jpg"]];
        [arr addObject:[UIImage imageNamed:@"3.jpg"]];
        [arr addObject:[UIImage imageNamed:@"4.jpg"]];
        [arr addObject:[UIImage imageNamed:@"5.jpg"]];
        [arr addObject:[UIImage imageNamed:@"6.jpg"]];
        [arr addObject:[UIImage imageNamed:@"7.jpg"]];
        return (NSArray *)arr;
}

- (void)viewDidLoad {
        IGUIScrollViewImage *svimage = [[IGUIScrollViewImage alloc] init];
        [svimage setContentArray:[self getImages]];
        [svimage setSizeFromParentView:self.myUIView];
        [svimage enablePageControlOnBottom];
        [self.myUIView addSubview:[svimage getWithPositionMemory]];
}

For more examples please check:

http://code.google.com/p/iphone-guru-uilibrary/wiki/IGUIScrollViewImage

As there might be more updated content ...

If you have any questions please feel free to contact me anytime trough any form on this website :)

Cheers,

Ondrej

Ondrej Rafaj

Ondrej Rafaj

Technical director @ Fuerte International

Back to top Comment

Comments ... Why not to get involved!
HTML Comment Box is loading comments...

Old comments:

Back to top

IE SUCKS, DON'T USE IT :) Digg this page