简体   繁体   English

滚动视图的水平居中内容

[英]Horizontally center content of a scroll view

I have a standard view embedded inside a scroll view and I am using Auto Layout. 我在滚动视图中嵌入了一个标准视图,并且正在使用“自动布局”。 All is working fine, and I am almost done with it. 一切工作正常,我几乎完成了。 There is just one small problem. 只有一个小问题。 My content view has a fixed height of 536 points, so in an iPhone 6 it is fully displayed without the need of scrolling, while in an iPhone 4S I have to scroll to view additional content. 我的内容视图具有536点的固定高度,因此在iPhone 6中可以完全显示而不需要滚动显示,而在iPhone 4S中,我必须滚动查看其他内容。

My problem is that the view is not horizontally centered is the iPhone 6 so it displays the extra space at the bottom (I filled it with grey color for clarity), as shown in the picture below (that is the underlying scroll view). 我的问题是,iPhone 6的视图没有水平居中,因此它在底部显示了额外的空间(为清晰起见,我用灰色填充了该空间),如下图所示(即下面的滚动视图)。

滚动视图

My question is: how can I horizontally center the content view without messing up the constraints? 我的问题是:如何在不破坏约束的情况下将内容视图水平居中? Currently the scroll view is pinned at the four borders of the view controller and the content view is pinned to the four borders of the scroll view. 当前,滚动视图固定在视图控制器的四个边界,内容视图固定在滚动视图的四个边界。

I am glad to provide any other information you need to help me solve the problem. 我很高兴提供您需要帮助我解决问题的任何其他信息。

EDIT: This is what it worked for me 编辑:这是对我有用的

CGFloat superViewHeight = self.view.bounds.size.height;
CGFloat scrollViewHeight = self.scrollView.bounds.size.height;

if (superViewHeight > scrollViewHeight)
    self.topConstraint.constant += (superViewHeight - scrollViewHeight) / 4;

You should manually adjust top constraint if your content view doesn't need scrolling. 如果您的内容视图不需要滚动,则应手动调整顶部约束。

CGFloat scrollViewHeight = CGRectGetHeight(scrollView.bounds);
CGFloat contentViewHeight = CGRectGetHeight(contentView.bounds);

if (scrollViewHeight >= contentViewHeight)
{
    topConstraint.constant += ((scrollViewHeight - contentViewHeight) / 2.f);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM