I have a UIViewController
, and I want to add a UIScrollView
to it (enable scroll support), is it possible?
I know it is possible, if you ha
An UIViewController
has a view
property. So, you can add a UIScrollView
to its view
. In other words, you can add the scroll view to the view hierarchy.
This is can achieved by code or through XIB. In addition, you can register the view controller as the delegate for your scroll view. In this way, you can implement methods for performing different functionalities. See UIScrollViewDelegate
protocol.
// create the scroll view, for example in viewDidLoad method
// and add it as a subview for the controller view
[self.view addSubview:yourScrollView];
You could also override loadView
method for UIViewController
class and set the scroll view as the main view for the controller you are considering.
Edit
I created a little sample for you. Here, you have a scroll view as a child of the view of a UIViewController
. The scroll view has two views as children: view1
(blue color) and view2
(green color).
Here, I suppose you can scroll in only one direction: horizontally or vertically. In the following, if you scroll horizontally, you can see that the scroll view works as expected.
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
scrollView.backgroundColor = [UIColor redColor];
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
scrollView.showsVerticalScrollIndicator = YES;
scrollView.showsHorizontalScrollIndicator = YES;
scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * 2, self.view.bounds.size.height);
[self.view addSubview:scrollView];
float width = 50;
float height = 50;
float xPos = 10;
float yPos = 10;
UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(xPos, yPos, width, height)];
view1.backgroundColor = [UIColor blueColor];
[scrollView addSubview:view1];
UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width + xPos, yPos, width, height)];
view2.backgroundColor = [UIColor greenColor];
[scrollView addSubview:view2];
}
If you need to scroll only vertically you can change as follows:
scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height * 2);
Obviously, you need to rearrange the position of view1
and view2
.
P.S. Here I'm using ARC. If you don't use ARC, you need to explicitly release
alloc-init objects.