的UIViewController
有view
属性。因此,您可以将UIScrollView
添加到其view
。换句话说,您可以将滚动视图添加到视图层次结构中。
这可以通过代码或通过XIB来实现。另外,您可以将视图控制器注册为滚动视图的代理。通过这种方式,您可以实现执行不同功能的方法。见UIScrollViewDelegate
协议。
// create the scroll view, for example in viewDidLoad method
// and add it as a subview for the controller view
[self.view addSubview:yourScrollView];
您也可以覆盖loadView
方法UIViewController
类,并设置滚动视图为您所考虑的控制器的主视图。
编辑
我创建了一个小样品给你。在这里,您将滚动视图作为UIViewController
视图的子视图。滚动视图有两个视图为儿童:view1
(蓝色)和view2
(绿色)。
在这里,我想你只能在一个方向上滚动:水平或垂直。在下面,如果您水平滚动,您可以看到滚动视图按预期工作。
- (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];
}
如果你只需要垂直您可以更改如下滚动:显然
scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height * 2);
,你需要重新安排的view1
和view2
位置。
P.S.我在这里使用ARC。如果你不使用ARC,你需要明确release
alloc-init对象。
你可以添加UIScrollView来查看UIViewController&你可以查看UIViewController到UIScrollView –
在做类似的事情之前,我会看看什么是控制器和什么是视图。他们是非常不同的东西。 – Mert
您可以将scrollview添加到视图控制器并将视图控制器添加到scrollview,只需将您的scrollview作为子视图添加到您现有的viewController – Talha