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)
相关推荐
东坡肘子2 天前
毕业 30 年同学群:一场 AI 引发的“真假难辨”危机 -- 肘子的 Swift 周报 #112
人工智能·swiftui·swift
Antonio9152 天前
【Swift】UIKit:UIAlertController、UIImageView、UIDatePicker、UIPickerView和UISwitch
ios·cocoa·swift
Antonio9152 天前
【Swift】UIKit:UISegmentedControl、UISlider、UIStepper、UITableView和UICollectionView
开发语言·ios·swift
1***81533 天前
Swift在服务端开发的可能性探索
开发语言·ios·swift
S***H2833 天前
Swift在系统级应用中的开发
开发语言·ios·swift
HarderCoder3 天前
SwiftUI 状态管理极简之道:从“最小状态”到“状态树”
swift
Antonio9153 天前
【Swift】 UIKit:UIGestureRecognizer和UIView Animation
开发语言·ios·swift
蒙小萌19933 天前
Swift UIKit MVVM + RxSwift Development Rules
开发语言·prompt·swift·rxswift
Antonio9153 天前
【Swift】Swift基础语法:函数、闭包、枚举、结构体、类与属性
开发语言·swift
Antonio9154 天前
【Swift】 Swift 基础语法:变量、类型、分支与循环
开发语言·swift