ScrollView example in iPhone

In this application we will see how to ScrollView worked in our application. This is the very simple application. In the application when user input in the textfield then see UITextField is hidden under the keyboard.This problem solved using the ScrollView. So let see how it will be worked.

In this application we will see how to ScrollView worked in our application. This is the very simple application. In the application when user input in the textfield then see UITextField is hidden under the keyboard.This problem solved using the ScrollView. So let see how it will be worked.

Step 1: Create a View base application using the template. Give the application name “ScrollViewExample”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Expand classes and notice Interface Builder created the ScrollViewExampleViewController class for you. Expand Resources and notice the template generated a separate nib, ScrollViewExampleViewController.xib, for the “ScrollViewExample”.

Step 4: Open the ScrollViewExampleViewController.h file, we have added scrollview for scrolling the view,and two textfield for display the textbox. So make the following changes in the file:

#import <UIKit/UIKit.h>

@interface ScrollViewExampleViewController : UIViewController {

        IBOutlet UIScrollView *scrollview;
    IBOutlet UITextField *textField1;
    IBOutlet UITextField *textField2;
       
        BOOL displayKeyboard;
        CGPoint  offset;
        UITextField *Field;
}

@property(nonatomic,retain) IBOutlet UIScrollView *scrollview;
@property(nonatomic,retain) IBOutlet UITextField *textField1;
@property(nonatomic,retain) IBOutlet UITextField *textField2;

Step 5: Double click your ScrollViewExampleViewController.xib file open it to the Interface Builder. First drag Scroll View from the library and place it to the view window and drag two TextField also, place it to the view window(See the figure below).Connect the File’s Owner icon to the View icon and select view. Select File’s Owner icon to the view and select scrollview. Next drag from the File’s Owner icon to the first textfield and select textfield1, do it once more time for the textfield2. Now save it, close it and go back to the Xcode.

Step 6: In the ScrollViewExampleViewController.m file make the following changes:

- (void) viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
               
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector
         (keyboardDidShow:)
         name: UIKeyboardDidShowNotification
         object:nil];
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector
         (keyboardDidHide:) name:
         UIKeyboardDidHideNotification
         object:nil];
       
        scrollview.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH,
                                                                                SCROLLVIEW_CONTENT_HEIGHT);
       

        displayKeyboard = NO;
}

-(void) viewWillDisappear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self];
}

-(void) keyboardDidShow: (NSNotification *)notif {
                if (displayKeyboard) {
                        return;
        }
       
       
        NSDictionary* info = [notif userInfo];
        NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [aValue CGRectValue].size;
       
        offset = scrollview.contentOffset;
       
                CGRect viewFrame = scrollview.frame;
        viewFrame.size.height -= keyboardSize.height;
        scrollview.frame = viewFrame;
       
        CGRect textFieldRect = [Field frame];
        textFieldRect.origin.y += 10;
        [scrollview scrollRectToVisible: textFieldRect animated:YES];
        displayKeyboard = YES;
}

-(void) keyboardDidHide: (NSNotification *)notif {
        if (!displayKeyboard) {
                return;
        }
       
        scrollview.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH, SCROLLVIEW_CONTENT_HEIGHT);
       
        scrollview.contentOffset =offset;
       
         displayKeyboard = NO;
       
}

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
         Field = textField;
        return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
        [textField resignFirstResponder];
        return YES;
}

Step 7: Now compile and run the application in the Simulator.

Download Updated SourceCodeScrollViewExample 2

WP Greet Box icon
Hello there! If you are new here, you might want to subscribe to the RSS feed for updates on this topic, and free programming tips and tricks and source code            snippets.

10 Responses to “ScrollView example in iPhone”

  1. Jennifer says:

    Interesting tutorial but the sourcecode doesn\’t actually scroll up. It compiles but isn\’t functionally what you show.

  2. Sushant says:

    When you run the application in the simulator,
    1.Then you click in the textfield
    2.Keyboard automatically showup, and UITextField is hidden under the keyboard.
    3.Enter the key from the keyboard, then you can see the TextField automatically scroll upside.

    Just try it, if still there have any problem please let us know.

  3. Jennifer says:

    Yes, I was able to make that happen. It seems odd that you should have to start typing for the field to become visible. I also don’t believe your textFieldShouldBeginEditing isn’t being called as the Return Key does not dismiss the keyboard.

  4. Sushant says:

    Yes, there have some problem , i have find out it. Thanks for your comment.!! Now you can download updated source code.

  5. cepnyci says:

    Place the code inside “keyboardDidShow” function into “keyboardWillShow” function. That will scroll the view as soon as you click in a Text Field.

    The function will be as follows:

    - (void)keyboardWillShow:(NSNotification *)notif {
    if (displayKeyboard) {
    return;
    }

    NSDictionary* info = [notif userInfo];
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;

    offset = scrollview.contentOffset;

    CGRect viewFrame = scrollview.frame;
    viewFrame.size.height -= keyboardSize.height;
    scrollview.frame = viewFrame;

    CGRect textFieldRect = [Field frame];
    textFieldRect.origin.y += 10;
    [scrollview scrollRectToVisible: textFieldRect animated:YES];
    displayKeyboard = YES;
    }

  6. sivasankar says:

    HI

    I HAVE TRIED FOR MORE THAN 7 TEXTFILEDS ,WHEN THE KEYBOARD GETS POPUP,THE TEXTFIELD IS NOT MOVING UP,MANUALLY WHEN WE SCROLL THE VIEW ONLY I CAN ABLE TO SEE THE 7TH TEXTFIELD(WHICH IS IN THE BOTTOM POSITION),KINDLY HELP ME OUT IN THIS.

    WITH REGARDS..

  7. Sim says:

    Great Tutorial…

  8. Adriano says:

    Thanks a lot Sim, you saved me a great amount of time.

    Cheers,
    Adriano

  9. Chris says:

    Still useful in May 2011 with XCode 4 but I had to download the source since all the headers of were missing

    I replaced the following deprecated line

    //NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];

  10. Noobdeveloper says:

    Hello,great tutorial,i tried in a view with more then 10 field and after u click on one and show the keyboard and then press on return the view becomes unscrollable!!!!and all the items goes a bit down in it (like if the Y offset get changed) and then the only way to make it scrollable again is to show the keyboard on another textfield !!

Leave a Reply

Security Code:

learn iphone programming

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Our Mobile Training Courses

EDUmobile.ORG offers the following 4 Mobile Training Courses. Our iPhone Training Course is very popular, with over 200 developers in training.

learn iphone programming
© 2010 EDUmobile.ORG