使用UIScrollView实现垂直滚动的正确方法

4
我知道我几分钟前问了一个问题,但在寻求社区的帮助之前,我想要更清楚地表达一些观点。我是iOS开发的新手,快要完成我的第一个应用程序。唯一阻碍我的是UIScrollView。我根本不理解它,需要你的帮助。
这是钻取应用程序的详细视图控制器,具有选项卡栏。我有大约8个字段(例如电话号码等)从.plist中获取。显然,这些需要足够的空间,我需要额外的房地产。我猜大概需要两个视图垂直排列的大小,但我不知道如何为UIScrollView分配这样的空间。我阅读过的一些教程说,您甚至不需要在头文件中定义它,我对此表示怀疑并且不理解。此外,我不知道如何使应用程序仅平稳地上下滚动。苹果的示例具有在水平图片之间翻转的常量移动周期。
我怀疑这并没有太大的区别,但我有一个在背景中的图像。我将在其上加载视图。
我的问题很广泛,因此我不指望您花时间为我编写所有代码(我也不会要求您)。只需提供快速有用提示的概述即可帮助我了解如何在我的项目上下文中加载此视图。
非常感谢!
4个回答

6
很简单。将UIScrollView添加到视图中。将您的字段等添加到UIScrollView中。在viewDidLoad或类似位置,您需要设置scrollview上的contentSize。这是可滚动的“虚拟”区域。它通常比scrollview的框架大。在您的情况下,您指示它应该大约是宽度的两倍。
例如,如果您有一个包含视图的scrollview,并且您希望通过滚动确保整个视图可见:
self.scrollView.contentSize = self.contentView.frame.size;

好的,如果View是ScrollView的父级,我该如何向其中添加内容呢(可能是一个愚蠢的问题)? - Rob Johnson

2
//setting scrollview zoom level
    self._scrollview.minimumZoomScale=0.5;

    self._scrollview.maximumZoomScale=6.0;

    self._scrollview.contentSize=CGSizeMake(320,500 );

您需要在.h类中放置滚动视图,并使用@property @synthesize来声明此滚动视图。然后,您就可以向上或向下滚动了。如果您只想进行垂直滚动,则需要进入界面生成器并取消水平滚动。


2

您可以为滚动视图设置一些设置,以限制滚动为水平或垂直。几个重要的设置如下:

// pseudcode here, start typing "[scrollView " then press escape to get a intelli-sense of all // the things you can set for the scrollview.

// values could be YES/NO or TRUE/FALSE, I can't remember which one but 
// I think it's YES/NO. Once you start scrolling, the phone will determine
// which way you're scrolling then lock it to that direction
[scrollView setDirectionalLockEnabled:YES];

// when you slide the view, if enough of the next part of the view is visible, 
// the scrollview will snap or bounce the scrollview to fit this new "page".
// think of swiping feature to navigate the iPhone home screens 
// to show different "pages" of iphone apps
[scrollView setPagingEnabled:YES];

// as a safe guard, make sure the width of your scrollview fits snuggly with the content 
// it is trying to display. If the width is more than necessary to display your table of 
// data vertically, sometimes the scrollview will cause the 
// horizontal scrolling that you don't want to happen and you get bi-directional scrolling

1
只需在添加所有控件/按钮/文本字段等后设置UIScrollView的内容大小。例如,您在UIScrollview中添加了10个文本字段,则UIScrollView的内容大小将为:
lastTextField.frame.origin.y+lastTextField.frame.size.height+20; 20 is for margin.

就这些了,如果您想了解与您的应用程序更相关的内容,请告诉我。


我应该如何将所有内容添加到滚动视图中,考虑到它的大小?在界面构建器中有特定的方法吗?(可能是一个非常愚蠢的问题) - Rob Johnson
是的,你也可以在界面构建器中完成。这有点棘手。首先将默认的UIView类更改为UIScrollView。然后在IB中设置UIViewController属性中将顶部状态栏设置为无来删除它。接着尽可能地拖放所有组件,然后再次将视图高度减小到460或416,具体取决于是否使用导航控制器。然后在viewDidLoad中设置UIScrollView的内容大小。 - Rahul Vyas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接