UIScrollView Example iPhone


 

UIScrollView Example iPhone

UIScrollView is the superclass of several UIKit classes which inherits form UIView : UIResponder : NSObject. Generally we need UIScrollView when our text length or form size is larger then the actual iphone application window.

UIScrollView is the superclass of several UIKit classes which inherits form UIView : UIResponder : NSObject. Generally we need UIScrollView when our text length or form size is larger then the actual iphone application window.

UIScrollView Example iPhone

UIScrollView is the superclass of several UIKit classes which inherits form UIView : UIResponder : NSObject. Generally we need UIScrollView when our text length or form size is larger then the actual iphone application window. That means you can adjust the size of view according to the requirement using ScrollView. While loading the scroll view, you required to set ContentSize of view as it tells where to stop scrolling.

Now, let's find out how to add scroll view to your application. You can accomplish it programmatically as well.. but here we will use interface builder.

First of all create a view based application, and in the viewController.h, you need to declare the object and property of the UIScrollView like...

IBOutlet UIScrollView *mscrollview;

and property...

@property(nonatomic, retain)IBOutlet UIScrollView *mscrollview;

now, in the viewController.m @synthesize mscrollview; and then release it.

So far.. we were just declaring it. But will it work now?
No! As it required to load the UIScrollView... see the given code to load the scrollview.

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(keyboardWasShown:)
name: UIKeyboardDidShowNotification
object: nil];

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(keyboardWasHidden:)
name: UIKeyboardDidHideNotification
object: nil];

mscrollview.frame = CGRectMake(0, 0, 320, 460);
mscrollview.contentSize = CGSizeMake(320, 800);

}

As you can see in the code, here we need to set the frame and contentSize as well... frame size is the actual size of iPhone application window, whereas contentSize tells up to what height the view will scroll.

After that open the viewcontroller.xib file and drag & drop the scrollview on it from the library. In interface builder right click and link the "mscrollview" outlet to scrollview.

You can place as many element as you want on the scrollview... save and build your application to see the output. Our application looks alike in the given image.

Download code

Ads