iOS: How To Make AutoLayout Work On A ScrollView
iOS: How To Make AutoLayout Work On A ScrollView
Posted on June 11th, 2014
Ok, I’ll admit. I’ve been seriously struggling with AutoLayout ever since it’s been introduced. I understand the concept, and I LOVE the idea of it, but when I actually do it, it almost never behaves as it does in my head.
So when I had a chance to go talk to an actual Apple Engineer about AutoLayout last week at WWDC, I made sure to go. I thought of my most painful experience using AutoLayout recently – when I was making a login screen with username and password fields on a ScrollView (so it scrolls up when the keyboard comes up) – and had the Apple engineer walk me through the example.
Here is what we made:
This is just two input fields centered on a ScrollView. You can see the AutoLayout at work here – the two input fields are centered correctly both on a 4s and a 5s device.
This “simple” solution took the Apple Engineer 40 minutes to solve! However, several senior engineers I know said that they’ve never been able to get AutoLayout working quite right on a ScrollView, so 40 minutes is actually not bad!
Here are the key tricks to getting AutoLayout to work on a ScrollView:
One View
The ScrollView should have only ONE child view. This is forced in Android, so I should have made the connection, but I just didn’t think of it – it’s too easy to put the two input text fields right onto the ScrollView, especially in Interface Builder.
Here is what the View Hierarchy should actually look like:
Again, make sure to put all your fields and custom views inside the one child view of the ScrollView!
Equal Widths
I’m going to start with the constraints from the outside (on the main view) in (to the stuff inside the ContentView).
The obvious starting point is to bind the ScrollView to the View – just select the ScrollView from the view hierarchy, and add the following constraints:
The key to getting the constraints to work properly however, is adding anEqual Width constraint between the main View and the ContentView. The ScrollView adjusts to the size of the content inside of it, so setting the ContentView to the Width of the ScrollView leaves the width of the ContentView ambiguous.
To create the Equal Width Constraint between the ContentView and the View, select the ContentView on the view hierarchy and Control + Drag to the View – you should get a pop-up that gives you the “Equal Widths” option:
Your constraints between the main View, ScrollView, and ContentView should look like this:
Content Insets
The constraints between the ScrollView and the ContentView are surprisingly straight forward – just bind the ContentView to the ScrollView (make sure the constant to the bottom layout guide is 0):
The constraints between the ContentView and ScrollView are now as follows with all constants set at 0:
If your storyboard is like mine, you might notice that the actual ContentView is not the full height of the main view or the ScrollView:
However, we do want to make sure the ContentView is centered when it’s rendered on a device. To do that we need to write some code to property set the Content Insets in the ViewController:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
// ViewController.swift import UIKit class ViewController: UIViewController { @IBOutlet var scrollView : UIScrollView @IBOutlet var contentView : UIView override func viewDidLoad() { super .viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { let scrollViewBounds = scrollView.bounds let containerViewBounds = contentView.bounds var scrollViewInsets = UIEdgeInsetsZero scrollViewInsets.top = scrollViewBounds.size.height/2.0; scrollViewInsets.top -= contentView.bounds.size.height/2.0; scrollViewInsets.bottom = scrollViewBounds.size.height/2.0 scrollViewInsets.bottom -= contentView.bounds.size.height/2.0; scrollViewInsets.bottom += 1 scrollView.contentInset = scrollViewInsets } } |
Once you add the proper constraints into the ContentView (see next step), your final result will look like this:
The ugly colors are meant to differentiate the ScrollView (green) from the ContentView (red). Again, in the storyboard, the ContentView is at the top of the ScrollView, but with our content insets set in code, it now becomes centered.
Centering Multiple Views
The final step is to add AutoLayout to the ContentView. This is the same as adding layout normally to any view, so I won’t go into much detail here.
The one thing I did learn that I’d like to share (although now it seems obvious) is how to center the two text fields in the view. Previously, I put the two text fields into a container view, and centered the container view in the parent view. However, that is not necessary.
Instead, you can center each text field horizontally in container (so they’re now centered and on top of each other), and then add a constant of 25 to one (so it’s moved up 25 pixels from the center), and add a constant of -25 to the other (so it’s moved down 25 pixels from the center).
This will leave you with a space of 50 pixels between the two text fields, but the space exactly in between them will be the center of the view.
Do you have any other AutoLayout tips? I’m always looking to learn more and improve, so please let me know in the comments!
You can view the source code on Github here.
Enjoy the article? Join over 8,500+ Swift developers and enthusiasts who get my weekly updates.
Subscribe
iOS: How To Make AutoLayout Work On A ScrollView的更多相关文章
- iOS开发——使用基于Autolayout的ScrollView
问题描述: 在使用Autolayout布局方式对ScrollView进行布局时,如果你想做一个可以垂直方向滚动的九宫格类似这样: 拿一行来说,一定不要想当然的尝试去给一行图标进行均匀排列的操作(指 ...
- iOS 屏幕适配:autoResizing autoLayout和sizeClass
1. autoResizing autoresizing是苹果早期的ui布局适配的解决办法,iOS6之前完全可以胜任了,因为苹果手机只有3.5寸的屏幕,在加上手机app很少支持横屏,所以iOS开发者基 ...
- 一篇文章详解iOS之AutoResizing、AutoLayout、sizeClass来龙去脉
前言 iPhone自诞生以来,随着其屏幕尺寸不断的多样化,屏幕适配的技术一直在发展更新.目前,iOS系统版本已经更新到9.3,XCode的最新版本已经是7.3,仅iPhone历史产品的尺寸就已经有4种 ...
- iOS开发——modifying the autolayout engine from a background thread
很多时候,我们需要用到多线程的东西,比如红外线检测是否有人经过.这种情况需要搞个子线程在后台不断的检测,这个线程可能是第三方提供的,你调用它给的方法,然后显示提示框的时候,问题就来了. 提示信息:Th ...
- iOS 8 UI布局 AutoLayout及SizeClass(二)
一.新特性Size Class介绍 随着iOS8系统的公布,一个全新的页面UI布局概念出现,这个新特性将颠覆包含iOS7及之前版本号的UI布局方式,这个新特性就是Size Class. Size Cl ...
- iOS 小 Tip:优化侧滑返回与 ScrollView 的兼容性
http://www.cocoachina.com/ios/20150909/13369.html 作者:@周楷雯Kevin 授权本站转载. 倘若在 ViewController 中添加了一个 Tab ...
- iOS学习笔记——AutoLayout的约束
iOS学习笔记——AutoLayout约束 之前在开发iOS app时一直以为苹果的布局是绝对布局,在IB中拖拉控件运行或者直接使用代码去调整控件都会发上一些不尽人意的结果,后来发现iOS在引入了Au ...
- iOS屏幕适配
## iOS屏幕适配 ### iOS屏幕适配发展史 1> iPhone4以前(没有iPad) * 不需要屏幕适配 2> iPad.iPhone5等设备出现 * 需要做横竖屏适配 * aut ...
- iOS开发UI篇—UIScrollView控件介绍
iOS开发UI篇—UIScrollView控件介绍 一.知识点简单介绍 1.UIScrollView控件是什么? (1)移动设备的屏幕⼤大⼩小是极其有限的,因此直接展⽰示在⽤用户眼前的内容也相当有限 ...
随机推荐
- MD5加密、时间戳转换、base64算法加密、解密
#region MD5加密 /// <summary> /// MD5加密 /// </summary> /// <param name="str"& ...
- java sqlhelper
dbinfo.properties部分: 注意每行末尾不可以有空格 #oracle configure UserName=scott Password=tiger Driver=oracle.jdbc ...
- 艺萌文件上传下载及自动更新系统(基于networkComms开源TCP通信框架)
1.艺萌文件上传下载及自动更新系统,基于Winform技术,采用CS架构,开发工具为vs2010,.net2.0版本(可以很容易升级为3.5和4.0版本)开发语言c#. 本系统主要帮助客户学习基于TC ...
- 对COM 组件的调用返回了错误 HRESULT E_FAIL
.net ppt转pdf时报以下错误: 对COM 组件的调用返回了错误 HRESULT E_FAIL 在服务器端打开PPT,选项--另存为--PDF,发现PowerPoint报了个错误: “无法找到打 ...
- 汽车驱动之家 http://bmw360.cn
汽车驱动之家 http://bmw360.cn
- Android中View的事件分发机制
简介 事件也称MotionEvent,事件分发机制就是对MotionEvent事件的分发过程,即当一个MotionEvent发生之后,系统需要把这个事件传递给一个具体的View. 点击事件的分发过程由 ...
- Single-page app(SPA)
有哪些值得推荐的一页式网站(Single-page app)? http://pro.weltrade.com/en/ 最近开到一下国外网站,一页到底,感觉很高大上,到底是怎么做出来的呢?技术要点是什 ...
- windows8.1下javaweb环境搭建及基本配置(jdk+tomcat+eclipse)
1.下载安装jdk在无空格的路径下,否则在linux下可能出问题.配置环境变量: a.新建系统变量——JAVA_HOME,值——D:\programming\java\jdk8 // win8下若建为 ...
- Html标签第一课
<p>段落标签</p> <h1>字体标签,1到6,越来越小</h1>.....<h6></h6><h>标签自动换行 ...
- cisco vpn client 自动登陆脚本
cisco vpn client 不能保存密码,每次都要输入太麻烦了 写了个wsh,可以自动输入密码,并登陆 '需要一个好听的名字 <job id="cisco"> ' ...