现在的位置: 首页 > 综合 > 正文

ios7 中的 Auto Layout 使用教程 第三节

2016年07月18日 ⁄ 综合 ⁄ 共 2523字 ⁄ 字号 评论关闭

       原文:http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1

       前面两节讲到了Auto Layout的简单应用,这一节我们来看看什么是Auto Layout

      

        正如你上两节写的的测试程序一样,Auto Layout 中基本用到的工具就是constraint(约束)。一个约束是描述了view和view之间的距离,大小等集合关系(不在是传统的frame、size、point)。举个列子来说:有这么一个constraint------"Label A 的右边缘和button B的左边缘相距20px"(这里面就没有提到具体位置)。

        Auto Layout 会考虑所有的Constraints,根据它们提供的数据做一些数学计算,从而得出控件在superview中,应有的尺寸和位置。你不必单独设置views 的frame,因为这一切Auto layout已经为你做好了。

        在以前(没有Auto layout时候),你不得不在方法 initWithFrame:中写一些代码设置view的frames(大小、位置)来适应设备的不同方向。

       

        对于上两节的应用下(如上图),当时的做法是(不用Auto Layout的情况下):

       

        同时还需要设置每个view的autosizing masks:

       

         

         但如果你用了Auto layout,上面的这种界面大小,位置存放,你就不需要考虑了,你只需要做:

        

          在auto layout中,控件的大小、位置已经不是那么重要了,重要的是约束。当然,你会说,当你拖动控件到xib上面时候,我还需要设置大小和位置啊?哈哈,这个在所难免,你肯定需要拖动一下放到你想放的位置,调整到你想要的大小。然后在给这些控件添加constraint,这些只是辅助工作,仅此而已。

 

          想怎么设计就怎么设计

          使用constraint最大的好处在于你不需要来回横竖屏(用快捷键Command+<-\->)来适配屏幕,还要写多余的代码。相反你只需要用Auto layout描述一下不同控件之间的位置大小关系即可,至于适配Auto Layout已经帮你完成了。我们可以称这种设计为"意念设计"。

          When you design by intent, you’re expressing what you want to accomplish but not necessarily how it should be accomplished. Instead of saying: “the button’s top-left corner is at coordinates (20, 230)”, you now say:这句话好复杂,大体意思说如果你的按钮位置 是 (20,230),那么现在只需要描述一下:

          "按钮是在superview 的垂直中心,距superview边缘20px",

          Auto Layout就会自动计算出button所有的位置,不管superview大小,都可以准确的定位位置。

          还有一些例子:

          "两个text field 大小总是一致" 

          "两个按钮总是一起移动"

          "四个label总是又对其"

          这使得你的用户界面的设计更加具有描述性。您只需定义约束,系统会自动为您计算框架。

          You saw in the first section that even a layout with just a few views needs quite a bit of work to layout properly in both orientations. With Auto Layout you can skip all that effort. If you set up your constraints properly, then the layout should
work without any changes in both portrait and landscape.
          Another important benefit of using Auto Layout is internationalization. Text in German, for example, is infamous for being very long and getting it to fit into your labels can be a headache. Again, Auto Layout takes all this work out of your hands,
because it can automatically resize your labels based on the content they need to display – and have everything else adapt with constraints.
         Adding support for German, French, or any other language is now simply a matter of setting up your constraints, translating the text, and… that’s it!
        

       The best way to get the hang of Auto Layout is to play with it, so that’s exactly what you will do in the rest of this tutorial.

       上面几段说了这么多,一句话,用Auto layout就是对的,就是好,有好多好处。

       注意:Auto Layout不仅可以用在屏幕旋转时,它还很容易缩放UI来适应屏幕大小,这不是巧合,iphone5和ios7.0都是用到了这种技术,来适配3.5和4.0不同屏幕的尺寸。

       好了就说到这里,这张没有例子有点枯燥,只是告诉你,什么叫做Constraint。

抱歉!评论已关闭.