What Auto Layout Doesn’t Allow

日常使用Snapkit做约束时经常会遇到约束更新错误或者不允许的操作,本文记录一下Autolayout中哪些操作是不被允许的

前置知识

Size Attributes and Location Attributes

Autolayout中Attributes分为两类:Size Attributes 和 Location Attributes

  • Size Attributes:表示的是尺寸信息,有Width、Height
  • Location Attributes:表示位置信息,有Leading、Left、Trailing、Right、Top、Bottom、Cente(x、y)、Baseline等等

Autolayout的本质

Autolayout的本质是如下形式的等式或不等式:

Item1.Attribute1 [Relationship] Multiplier * Item2.Attribute2 + Constant

Relationship可以是等式,比如:

  • View1.leading = 1.0 * View2.leading + 0
  • View1.width = 1.0 * View2.width + 20

也可以是不等式,比如:

View1.leading >= 1.0 * View2.trailing + 0

需要注意的是式子两边不总是有Attribute,如下所示:

  • View.height = 0.0 * NotAnAttribute + 40.0(✅)
  • View1.height = 0.5 * View2.height(✅)

上述两个约束都是正确的

规则

1. Size Attribute与Location Attribute之间不能做约束

原文:You cannot constrain a size attribute to a location attribute.

错误举例:View1.width = 1.0 * View2.trailing + 0(❌)

2. 不能对Location Attribute设置常量

原文:You cannot assign constant values to location attributes.

错误举例:View1.leading = 0.0 * NotAnAttribute + 20(❌)

3. Location Attribute中不能使用非1的mutiplier

You cannot use a nonidentity multiplier (a value other than 1.0) with location attributes.

错误举例:View1.leading = 0.5 * View2.leading + 20(❌)

4. Location Attribute中不同方向之间不能做约束

For location attributes, you cannot constrain vertical attributes to horizontal attributes.

错误举例:View1.centerX = 1 * View2.centerY + 20(❌)

5. Leading(Trailing)不能与Left(Trailing)做约束

For location attributes, you cannot constrain Leading or Trailing attributes to Left or Right attributes.

错误举例:View1.centerX = 1 * View2.centerY + 20(❌)

修改Constraints需要注意什么

除了上述规则外,在运行时也可能会更新约束,有如下这些支持的修改约束操作:

  • 激活/停用约束(Activating or deactivating a constraint)
  • 修改约束的常量部分(Changing the constraint's constant value)
  • 修改约束的优先级(Changing the constraint's priority)
  • 将视图从页面层级中移除(Removing a view from the view hierarchy)
相关推荐
YGGP12 小时前
【Swift】LeetCode 240.搜索二维矩阵 II
swift
YGGP1 天前
【Swift】LeetCode 73. 矩阵置零
swift
非专业程序员Ping2 天前
HarfBuzz 实战:五大核心API 实例详解【附iOS/Swift实战示例】
android·ios·swift
Swift社区3 天前
LeetCode 409 - 最长回文串 | Swift 实战题解
算法·leetcode·swift
YGGP5 天前
【Swift】LeetCode 54. 螺旋矩阵
swift
Swift社区5 天前
Foundation Model 在 Swift 中的类型安全生成实践
开发语言·安全·swift
HarderCoder6 天前
【Swift 可选链】从“如果存在就点下去”到“安全穿隧”到空合运算符
swift
HarderCoder6 天前
Swift 反初始化器详解——在实例永远“消失”之前,把该做的事做完
swift
HarderCoder6 天前
Swift 并发编程新选择:Mutex 保护可变状态实战解析
swift