Images horizontal scrollbar iPhone

| August 4, 2011 | 20 Comments

Goal:
We want to make a horizontal Scrollbar at the bottom of iPhone screen from where we can choose an image and when we click on any image it should be displayed in detail.So lets start

ScollView Tutorial

ScollView Tutorial

First of all create a new project of Windows-based application and select iPhone from Xcode. Name the project “ImagesScrollView”.

Now add a new UIViewController with Nib and name it “ScrollViewController”.Open the nib file and drag one UIImageView and one UIScrollView from interface builder.

Now open the UIScrollView.h and change following

#import <UIKit/UIKit.h>
#import "ScrollView.h"

@interface ScrollViewController : UIViewController <UIScrollViewDelegate> {

IBOutlet ScrollView *scrollView;
IBOutlet UIImageView *imageView;
NSMutableArray *images;
NSArray *imagesName;
}
-(void)ShowDetailView:(UIImageView *)imgView;
@end

I have declared two outlets one for connecting scrollview that we added on nib and one for image view where we will display larger images. Click on Scrollview and in the attribute inspector in 4th tab change the class to ScrollView that is custom class.

Now open ScrollView.m and create two arrays one will be containing the name of images that we added in resource folder and other will contain the UIImage objects which we will later show in ImageView.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		imagesName = [[NSArray alloc]initWithObjects:@"on.png",@"one.png",@"two.png",@"three.png",
				  @"four.png",@"five.png",@"six.png",@"seven.png",nil];
		images = [[NSMutableArray alloc]init];
    }
    return self;
}

Now Edit the ViewDidLoad method

- (void)viewDidLoad {
    [super viewDidLoad];
	scrollView.delegate = self;
	scrollView.scrollEnabled = YES;
	int scrollWidth = 120;
	scrollView.contentSize = CGSizeMake(scrollWidth,80);	 

	int xOffset = 0;
	imageView.image = [UIImage imageNamed:[imagesName objectAtIndex:0]];

	for(int index=0; index < [imagesName count]; index++)
	{

		UIImageView *img = [[UIImageView alloc] init];
		img.bounds = CGRectMake(10, 10, 50, 50);
		img.frame = CGRectMake(5+xOffset, 0, 160, 110);
		NSLog(@"image: %@",[imagesName objectAtIndex:index]);
		img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
		[images insertObject:img atIndex:index];
		scrollView.contentSize = CGSizeMake(scrollWidth+xOffset,110);
		[scrollView addSubview:[images objectAtIndex:index]];

		xOffset += 170;
	}

}

I assigned the scroll content width 120 at start as I will one imageview at the bottom I will increase its content width at bottom in horizontal direction. At first before starting the loop I am displaying first image.

Now comes the fun part. I want to check which image is clicked from scrollview so that I can display that image in above imageview. For that I will make a custom class otherwise I will not be able to detect its touch event because images are at inner most level in responder chain so I have to change the touch responder object which will be scrollview for that I have overriden this function in custom class

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[self.nextResponder touchesBegan:touches withEvent:event];
}

Again in ScrollViewController.m add this function to check which image is clicked.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

	UITouch * touch = [[event allTouches] anyObject];

	for(int index=0;index<[images count];index++)
	{
		UIImageView *imgView = [images objectAtIndex:index];
		NSLog(@"x=%f,y=%f,width =%f,height=%f",imgView.frame.origin.x,imgView.frame.origin.y,imgView.frame.size.width,imgView.frame.size.height);
		NSLog(@"x= %f,y=%f",[touch locationInView:self.view].x,[touch locationInView:self.view].y) ;

		if(CGRectContainsPoint([imgView frame], [touch locationInView:scrollView]))
		{
			[self ShowDetailView:imgView];
			break;
		}
	}
}

Whichever image is clicked following function will display large image.

-(void)ShowDetailView:(UIImageView *)imgView
{
	imageView.image = imgView.image;
}

I hope it helps. Any question, comments or thoughts are welcomed.
Click here to download source code.

Developed by: Asif Noor (asef.noor@gmail.com)

Tags: , , , , , , , , ,

Category: iPhone Tutorials for Beginners

Comments (20)

Trackback URL | Comments RSS Feed

  1. Ashish says:

    you are awesome.

    Thnx alot

  2. Dinesh says:

    Hi
    Thanks for the great tutorial.
    But I want to open a new view controller on touch on the images of scroll view.
    What code i should write for that.
    Please solve my problem
    regards
    Dinesh Kaushik

    • Asif Noor says:

      You can do is following

      In your touch began method you can simply create a new view controller and push it onto a navigation controller.

      Hope it helps.

  3. Tigris says:

    How will this work in storyboard? I have the scroller going horizontal but there’s no images that comes out and I written the name of the images in the code, I’m not sure how it works in the Storyboard.

    please help..
    Thanks!
    Tigris

  4. Tigris says:

    My scrollView scrolls horizontally but it doesn’t show the image I had written in the “imagesName”

  5. Goti says:

    Oh thnx buddy,,,I got exactly what I want….

  6. see says:

    My scrollView scrolls horizontally but it doesn’t show the image I had written in the “imagesName”

    • Asif Noor says:

      HI Tigris,
      You should post your code here so that I can look at it and figure out where is the problem exactly.

  7. sapphire says:

    thanks you so much.Nice one.

  8. nithin MK says:

    It works nicely,thanks for the great tutorial

    i have a doubt

    i have some image urls in an url,i have parsed those urls into an array,i want to show them as u said
    please help me to do this(i am new in programming)

    [stringarray-Array where i parsed the image urls its by a for loop]

    -(void)returnimages:(NSArray *)arry{

    int x = 0;
    for(int i = 0; i <imagearry.count; i ++){
    NSDictionary *dict = [imagearry objectAtIndex:i];
    NSLog(@"%@",[dict objectForKey:@"img_url"]);
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches"];

    stringarry = [[imagearry objectAtIndex:i] objectForKey:@"img_url"];

    int x = 0;

    imageView.image = [UIImage imageNamed:[stringarry objectAtIndex:0]];

    for(int i=0; i < [stringarry count]; i++)
    {

    UIImageView *img = [[UIImageView alloc] init];
    img.bounds = CGRectMake(10, 10, 50, 50);
    img.frame = CGRectMake(5+x, 0, 160, 110);
    NSLog(@"image: %@",[stringarry objectAtIndex:i]);

    NSURL * url = [NSURL fileURLWithPath:[filePath stringByAppendingPathComponent:[stringarry objectAtIndex:i]]];
    [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

    img.image = [UIImage imageNamed:[stringarry objectAtIndex:i]];
    [stringarry insertObject:img atIndex:i];
    [scrollView addSubview:[stringarry objectAtIndex:i]];

    x += 170;
    }

    }

    }

  9. nithin MK says:

    Here i am posting my full code…..

    // JsonParsing.h

    #import
    #import “AppDelegate.h”
    @protocol ImageParsing

    -(void) returnimages:(NSArray *) arry;

    @end
    @interface JsonParsing : NSObject{

    iddelegate;
    NSMutableData *datas;
    }

    @property (retain, nonatomic) iddelegate;

    -(void) imageparsing;

    @end

    // JsonParsing.m

    #import “JsonParsing.h”
    #import “JSON.h”
    @implementation JsonParsing
    @synthesize delegate;

    -(void)imageparsing{
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.254/iphonetest/slide_show1.php"];
    NSURLRequest *urlReqest = [[NSURLRequest alloc] initWithURL:url];
    datas = [[NSMutableData alloc] init];
    [NSURLConnection connectionWithRequest:urlReqest delegate:self];

    }

    -(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@”Error” message:@”Connection failure” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil, nil];
    [alertview show];
    }

    -(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response{

    }

    -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)data{

    [datas appendData:data];
    }

    -(void)connectionDidFinishLoading:(NSURLConnection *) connection{

    NSString *responseString = [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSArray *array = [responseString JSONValue];
    if (self.delegate && [self.delegate respondsToSelector:@selector(returnimages:)]) {

    [self.delegate returnimages:array];
    }
    }

    @end

    // ViewController.h

    #import
    #import “JsonParsing.h”
    @interface ViewController : UIViewController{

    NSArray *imagearry;
    NSString *imagestring;
    NSMutableArray *stringarry;

    IBOutlet UIScrollView *scrollView;
    IBOutlet UIImageView *imageView;
    NSArray *imagesName;

    }
    @property (weak, nonatomic) IBOutlet UIScrollView *sclvw;
    -(void)ShowDetailView:(UIImageView *)imgView;

    @end

    // ViewController.m

    #import “ViewController.h”

    @interface ViewController ()

    @end

    @implementation ViewController
    @synthesize sclvw;

    – (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
    }
    return self;
    }

    – (void)viewDidLoad
    {
    [super viewDidLoad];
    JsonParsing *imgcon = [[JsonParsing alloc] init];
    imgcon.delegate = self;
    [imgcon imageparsing];

    [super viewDidLoad];
    scrollView.delegate = self;
    scrollView.scrollEnabled = YES;
    int scrollWidth = 120;
    scrollView.contentSize = CGSizeMake(scrollWidth,80);

    }

    -(void)returnimages:(NSArray *)arry{

    imagearry = [arry mutableCopy];

    int x = 0;
    for(int i = 0; i <imagearry.count; i ++){
    NSDictionary *dict = [imagearry objectAtIndex:i];
    NSLog(@"%@",[dict objectForKey:@"img_url"]);
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches"];

    stringarry = [[imagearry objectAtIndex:i] objectForKey:@"img_url"];

    int x = 0;

    imageView.image = [UIImage imageNamed:[stringarry objectAtIndex:0]];

    for(int i=0; i < [stringarry count]; i++)
    {

    UIImageView *img = [[UIImageView alloc] init];
    img.bounds = CGRectMake(10, 10, 50, 50);
    img.frame = CGRectMake(5+x, 0, 160, 110);
    NSLog(@"image: %@",[stringarry objectAtIndex:i]);

    NSURL * url = [NSURL fileURLWithPath:[filePath stringByAppendingPathComponent:[stringarry objectAtIndex:i]]];
    [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

    img.image = [UIImage imageNamed:[stringarry objectAtIndex:i]];
    [stringarry insertObject:img atIndex:i];
    [scrollView addSubview:[stringarry objectAtIndex:i]];

    x += 170;
    }

    }

    }

    – (void)didReceiveMemoryWarning
    {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

    @end

  10. Ambuj Shukla says:

    The post is very helpful but swipe in horizontally it moves many images but I want to scroll images one by one on swiping it.

    • Asif Noor says:

      It moves many images because it is implemented by using scrollview. If you combine scrollview with page control then it will change image one by one on each swipe.

  11. HongKonger says:

    hi

    i am a newcomer~

    Thank you for yr tutorial firstly~

    Question:

    i am using Xcode 4.5.2

    where to find “UIScrollView.h”

    Sorry for stupid :D

    • Asif Noor says:

      Actually it is basically SDK class of scrollview. Press Command + Enter on UIScrollview, it will redirect you on its .h file.

      • HongKonger says:

        Thanks very much!

        it successfully opens the UIScrollView.h!

        but….

        when i modify it as your demonstration,

        it shows me :

        ” The file “UIScrollView.h” could not be unlocked.

        could not add write permission to the file because you do not own it. Try modifying the permissions of the file in the Finder or Terminal.”

        why is that!?

        Please help ;(~

        • Asif Noor says:

          Hi,
          There are two solutions to this.

          1.Select the locked file, on right side of Xcode there is lock sign to unlock it.
          2. Select the locked file in Xcode, go to File from top bar, there is option to Unlock it.

          Hope it helps.

  12. Andre says:

    Hi there, many thanks for this tutorial.
    I found some difficulties trying this example you’ve provided.
    I’ve created an app with several views, where in one of them I want to add an image gallery with an horizontal scrollbar, just like in this example. But the problem I’m having is to make my File Owner to “recognize” your ScrollViewController, I.E., as I have now to XIBs, and this image Gallery is defined in ScrollViewController.xib, how can I connect my actions to this view?

    I think I’ve made all the correct connections in IB (at least the behavior was the expected), it compiles perfectly but when I push the button “Gallery” in the simulator it shows me an empty view.
    I simply want to push a button (with its action defined in “Main_ViewController.h/m”) and make it appear the UIScrollView defined in your class. I’m searching both physical books and Google for the last 3 days and could not manage a solution so far..
    Thanks for any help
    Andre

Leave a Reply

Sex Chat Live Jasmin WP-Clear 3.0 Theme