#1 [iOS充电]AutoLayout中的priority,multiplier是什么?

1,544 阅读2分钟

AutoLayout

作为一个切图仔,对于AutoLayout一直没系统学习过,而最近做的很多切图的工作中,在AutoLayout相关的问题经常卡壳。

面试的时候,也经常被问及AutoLayout一些相关概念,答的不怎么好。

正好一个需求做完了,来充电一下对AutoLayout不熟悉的概念。

multiplier

整理自:stackoverflow

  • 如果需要实现两个view,1:1的宽度,怎么办呢? 很容易,加一个EqualWidths的约束
  • 如果需要实现两个view,2:3的宽度,怎么办呢? 这个时候就需要multipiler了

image.png

如图,设置multiplier为2:3,就达到效果了

  • 用Masonry怎么写?

image.png

随便查查就有结果了

make.left.equalTo(view.mas_right).multipliedBy(4.0/3.0)

priority

那么,同样常见的priority又是啥意思呢?Google一下: What is constraint priority and how to use it

关键笔记:

  • This is the sixth (also last) part of Making Sense of Auto Layout Series. 看来AutoLayout也就这些内容,不用怕啦
  • Constant priority is a number to determine how important is that constraint. The number can range from 1 to 1000, the higher the number goes, the more important a constraint is. priority是constraint的重要性,1到1000
  • What does important mean? When there are conflicting constraints, Auto Layout Engine will attempt to break / ignore constraint with lower priority number first, hence making constraint with higher priority having higher importance. 重要性的意思是,当有矛盾的constraints时,AutoLayout引擎会忽略或者破坏低优先级的constraint
  • If there are two conflicting constraints with the same priority number (making it a tie), Xcode will show you red lines with numbers. 当两条constraints不仅矛盾,而且优先级相等,那么Xcode会显示出红线

原来如此,妙啊妙啊

  • When you define a new constraint in Interface Builder / Storyboard, Xcode will auto assign the constraint priority as 1000. 1000 is the highest constraint priority, meaning it is mandatory as no other constraint can have higher priority than this and this constraint will never be ignored in favor of others. 当你创建一条新的约束,Xcode会赋予默认优先级1000。1000意味着强制的、最高优先级,无法被忽视
  • On the other hand, constraints with priority less than 1000 (1-999) are called as optional constraint as it might be ignored in favor of other constraint which have higher constraint priority. 1000以下的优先级是optional constraint(可选约束),它可能被更高优先级的constraint忽略
  • When you normally create a constraint (Xcode default set it to 1000 priority, mandatory constraint), it will show as a blue solid line like this :
  • If you change the constraint priority to any number lower than 1000 (optional constraint), it will show dashed line like this : image.png

妈耶,我怎么才知道

  • Constraint priority is useful when you have possible conflicting constraint and you want to tell Xcode which of them can be safely ignored when conflict arise in order to solve conflict. 当有可能矛盾的constraint时,priority是很实用的。你可以用来告诉Xcode哪些constraint可以被安全地忽略,以解决矛盾
  • Usually you will want to modify constraint priority of a constraint which uses larger or equal to (>=) / smaller or equal to (<=) instead of plain "equal" (==). 通常对于使用“>=”或者“<=”的约束,你可能会调整它的priority