转载自: http://natashatherobot.com/ios-autolayout-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 an Equal 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.

转载于:https://www.cnblogs.com/zsw-1993/p/4879192.html

iOS: How To Make AutoLayout Work On A ScrollView相关推荐

  1. 【iOS】自动布局(AutoLayout)和手写布局(frame)

    1.1 AutoLayout原理 iOS 中视图所需要的布局信息只有两个,分别是 origin/center 和 size,在这里我们以 origin & size 为例,也就是 frame ...

  2. iOS: 让自定义控件适应Autolayout注意的问题

    第一个是initWithCoder方法:因为开发者多在Storyboard中使用Autolayout,而Storyboard中的View初始化不是使用常见的initWithFrame方法的,而是使用i ...

  3. iOS 8 UI布局 AutoLayout及SizeClass(二)

    一.新特性Size Class介绍 随着iOS8系统的公布,一个全新的页面UI布局概念出现,这个新特性将颠覆包含iOS7及之前版本号的UI布局方式,这个新特性就是Size Class. Size Cl ...

  4. iOS UITableView+FDTemplateLayoutCell 配合AutoLayout分分钟教你实现类似微信朋友圈的动态高度自适应

    11.30日更新,实现了简单的微信朋友圈,点赞,评论,图片,高度自适应,下拉展开等各种效果Demo 点击打开链接 11.10更新 这种高度自适应的Label切记一定要加上这个属性 preferredM ...

  5. arm linux运行安卓app,Android x86 下运行纯ARM版APP

    Android x86 默认不带houdini,运行纯ARM版会提示: 很抱歉,"xxxx"已停止运行 设置->应用兼容性->打开 终端模拟器 $ su # enabl ...

  6. iOS开发~sizeClass和autolayout

    sizeClass和autolayout,看来不得不开始放弃frame的写法,收集点资料集中学习下 Adaptivity User Interfaces苹果官方文档:https://developer ...

  7. 寒哥细谈之AutoLayout全解

    看到群中好多朋友还停留在Frame布局的痛苦时代,以及有些开发者接手别人的就项目发现布局一团乱. 而且没有启动图的时候并不是真正真正适配iPhone 6(S).iPhone6(S) Plus等设备 . ...

  8. iOS开发UIScrollView的底层实现

    起始 做开发也有一段时间了,经历了第一次完成项目的激动,也经历了天天调用系统的API的枯燥,于是就有了探索底层实现的想法. 关于scrollView的思考 在iOS开发中我们会大量用到scrollVi ...

  9. iOS开发UI篇—UIScrollView控件介绍

    iOS开发UI篇-UIScrollView控件介绍 一.知识点简单介绍 1.UIScrollView控件是什么? (1)移动设备的屏幕⼤大⼩小是极其有限的,因此直接展⽰示在⽤用户眼前的内容也相当有限 ...

最新文章

  1. [转]《JAVA与模式》之责任链模式
  2. 处理ABAP Netweaver gateway service使用过程中遇到的400 error - invalid key predicate type for guid
  3. [转]Android中pendingIntent的深入理解
  4. JVM对象占用内存计算
  5. Firefox Test Pilot 计划正式关闭
  6. 冒泡排序和选择排序的JAVA程序
  7. FlashBuilder找不到所需要的AdobeFlashPlayer调试器版本的解决方案
  8. BZOJ 2683: 简单题(CDQ 分治)
  9. java modbus通讯协议_Modbus通 讯 协 议
  10. 现代优化算法 (二): 遗传算法 及应用举例
  11. 转载C# -- 系统托盘NotifyIcon控件
  12. 推荐一款手机app自动点击神器
  13. python 文件名变量_如何将变量文件名传递给python ete?
  14. oracle 取前行,【企业信息化研究所】TF-SWUFE Oracle Club抵着寒风前行—甲骨文俱乐部第九周分享会...
  15. oracle 分组 最新,Oracle分组查询
  16. 守得住孤独,把得住清欢
  17. http://www.youku.com/playlist_show/id_4637211.html
  18. 从网络访问此计算机guest密码,Windows XP网络共享访问总是弹出输入Guest密码对话框的解决...
  19. IAR 显示行号设置
  20. [算法竞赛入门经典] UVA 12174 - Shuffle

热门文章

  1. bootstrap --- 按钮
  2. 22 React高阶组件
  3. 利用RTL2832u电视棒芯片追踪民航飞机轨迹
  4. node+koa2+mysql搭建博客后台
  5. JAVA入门[6]-Mybatis简单示例
  6. uboot中变量env(收集)
  7. SourceProvider.getJniDirectories
  8. 《DirectX 9.0 3D游戏开发编程基础》 第二章 绘制流水线 读书笔记
  9. 打印机每天都要重新连接
  10. [Win 7]Windows7 RC 简体中文版测试正式开始了哦!!