如何让UIScrollView尊重包含UIView的布局?

问题描述:

我正在使用UIView来控制我的视图(以及视图控制器)的布局。我想让UIScrollView只使用垂直屏幕的一半。如果我使用屏幕的上半部分,但不是下半部分,那很好。如何让UIScrollView尊重包含UIView的布局?

下面是来自UIViewController中的相关代码:

- (void)loadView { 
CGRect fullFrame = [[UIScreen mainScreen] applicationFrame]; 
//trying to put the scroll view on the bottom half of the screen, but does not work. 
CGRect halfFrame = CGRectMake(0, fullFrame.size.height/2 , 
    fullFrame.size.width, fullFrame.size.height/2); 
//use this instead for the scroll view to go to the top half of the screen (and work properly) 
//CGRect halfFrame = CGRectMake(0, 0 , fullFrame.size.width, fullFrame.size.height/2); 

UIScrollView* sv = [[UIScrollView alloc] initWithFrame:halfFrame]; 
[sv setContentSize:CGSizeMake(3 * halfFrame.size.width, halfFrame.size.height)]; 

CGRect stencilFrame = halfFrame; 
UIView *leftView = [[UIView alloc] initWithFrame:stencilFrame]; 

stencilFrame.origin.x += stencilFrame.size.width; 
UIView *centerView = [[UIView alloc] initWithFrame:stencilFrame]; 

stencilFrame.origin.x += stencilFrame.size.width; 
UIView *rightView = [[UIView alloc] initWithFrame:stencilFrame]; 

//mix up the colors 
[leftView setBackgroundColor:[UIColor redColor]]; 
[centerView setBackgroundColor:[UIColor greenColor]]; 
[rightView setBackgroundColor:[UIColor blueColor]]; 

//add them to the scroll view 
[sv addSubview:leftView]; 
[sv addSubview:centerView]; 
[sv addSubview:rightView]; 

//turn on paging 
[sv setPagingEnabled:YES]; 

UIView *containerView = [[UIView alloc]initWithFrame:fullFrame]; 
[containerView addSubview:sv]; 
[self setView:containerView];  
} 

预先感谢您的任何建议或帮助。

我想通了。问题的症结在于,滚动视图内的视图是使用与滚动视图本身相同的框架进行初始化的。当scrollView初始化为halfFrame时,原点为(0,为全屏大小的一半),这是正确的,因为它与应用程序窗口本身有关。但是,放置在scrollView(如leftView)中的视图初始化为halfFrame,但在这种情况下,原点相对于scrollView,将其有效地放在屏幕上。设置原点为(0,0)固定的:

的CGRect stencilFrame = CGRectMake(0,0,fullFrame.size.width,fullFrame.size.height/2);

contentSize必须包含滚动视图内的视图的矩形。也就是所有可滚动控件的总大小。 UIScrollView的框架决定需要多少滚动才能让用户浏览所有内容。

+0

恭敬地,我不确定我是否遵守。不是“可滚动控件的总大小”等于单个视图的3 *帧宽度(因为有3个视图)? – 2010-11-23 03:50:50

如果您有导航栏或选项卡栏,则没有“完整框架”可用。一般来说,使用[UIScreen mainScreen]作为布局信息的代码可能是错误的。

此外,如果(例如)正在进行呼叫或启用网络共享,状态栏可以更改大小。

相反,使用任何理智的价值为全画幅,并启用自动尺寸:

CGRect fullFrame = {{0,0}, {320,480}}; 

... 

sv.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin; 

编辑:您还可能需要继承的UIScrollView和实施-setFrame:,使其还可以设置内容大小和-layoutSubviews做正确的布局。

+0

我明白你对使用mainScreen框架大小的观点。但是,这对于任何帧大小(我已经找到)都不起作用,即使使用自动识别掩码。 – 2010-11-23 05:14:10