Adding UIScrollView to a UIViewController



我有一个UIViewController,我想添加一个UIScrollView到它(启用滚动支持),这是可能的吗?

我知道这是可能的,如果你有一个UIScrollView添加一个UIViewController到它,但我也感兴趣,如果反向是真的,如果我可以添加一个UIScrollView到现有的UIViewController,这样我得到滚动功能。

编辑

我想我已经找到了一个答案:添加一个UIViewController到UIScrollView

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];

你也可以为UIViewController类重写loadView方法,并将滚动视图设置为你正在考虑的控制器的主视图。

编辑

我为你创建了一个小样本。在这里,您有一个滚动视图作为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);

显然,你需要重新安排view1view2的位置。

注:这里我用的是ARC。如果你不使用ARC,你需要显式的release alloc-init对象

最新更新