【iOS 开发】SnapKit 是怎样炼成的

简介: 前言这是对 Swift 布局框架 SnapKit 的源码的一点分析,尝试搞清,一个好的布局框架,背后都做了些什么。介绍 SnapKit 中的一些类ConstraintView等同于 UIViewConstraintAttributes用于构造约束关系的各种元素(上下左右等)ConstraintDescription包含了包括 ConstraintAttributes 在内的各种与约束有关的元素,一个 ConstraintDescription 实例,就可以提供与一种约束有关的所有内容。

前言

这是对 Swift 布局框架 SnapKit 的源码的一点分析,尝试搞清,一个好的布局框架,背后都做了些什么。

介绍 SnapKit 中的一些类

ConstraintView
等同于 UIView

ConstraintAttributes
用于构造约束关系的各种元素(上下左右等)

ConstraintDescription
包含了包括 ConstraintAttributes 在内的各种与约束有关的元素,一个 ConstraintDescription 实例,就可以提供与一种约束有关的所有内容。

ConstraintMaker
构造约束关系的起点,提供了 <code>makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void)</code> 方法来为程序员提供了描述约束的空间,也可以通过 left right top bottom centerX centerY 等属性,去生成一个 ConstraintMakerExtendable 实例(见下面)

ConstraintMakerExtendable(继承 ConstraintMakerRelatable)
提供 left right top bottom leading trailing edges size margins 等内容,用以产生一个 ConstraintMakerRelatable 类型的实例

ConstraintMakerRelatable
直接用于构造约束关系,也是常用方法 <code>equalTo(_ other: ConstraintRelatableTarget) -> ConstraintMakerEditable</code> 与 <code>equalToSuperview</code> 的来源。核心方法是 <code>relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable</code>,返回 ConstraintMakerEditable 类型的实例

ConstraintMakerEditable(继承 ConstraintMakerPriortizable)
在设定约束的宽度、高度以及偏移的时候,提供相应的加减乘除方法,返回 ConstraintMakerPriortizable 类型的实例

ConstraintMakerPriortizable(继承 ConstraintMakerFinalizable)
提供方法来设置约束的 priority,返回 ConstraintMakerFinalizable 类型的实例

ConstraintMakerFinalizable
一个只有一个类型为 ConstraintDescription 的属性的类,正如它的类名,有一个 ConstraintMakerFinalizable 实例,就得到了对于一个约束的完整描述。


至此,我们已经知道 SnapKit 是靠什么来确定了三个东西:

  1. 谁在做约束(ConstraintView)
  2. 怎么做约束(ConstraintMaker)
  3. 约束是什么(ConstraintDescription)
let aView = UIView()
aView.snp.makeConstraints({ make in
    make.width.equalToSuperview().dividedBy(2).priority(100)
})

当我们写下这样的语句时,先忽略掉 <code>snp</code> 是什么不管,里面设定 aView 的宽度为它的父视图的一半的这行约束语句,执行了这样的逻辑:

  1. ConstraintMaker 提供 <code>makeConstraints</code> 方法来让我们写约束的同时,开始维护了一个 ConstraintDescription 数组,叫 <code>descriptions</code>
  2. make 本身是 ConstraintMaker 类型的
  3. 在我们写下 <code>.width</code> 时,<code>descriptions</code> 数组第一次加入内容(<code>self.description</code>),同时我们用这个内容生成了一个 ConstraintMakerRelatable 实例
  4. 在我们写下 <code>.equalToSuperview()</code> 时,上一步中的内容(<code>self.description</code>)继续添加信息,同时我们用它生成了一个 ConstraintMakerEditable 实例
  5. 之后的 <code>.dividedBy(2).priority(100)</code> 使得之前的 ConstraintMakerEditable 实例变成了一个 ConstraintMakerFinalizable 实例,这个实例的 description 属性的类型是 ConstraintDescription,它包含了我们所描述的全部内容。但由于 ConstraintMakerEditable 本身就继承自 ConstraintMakerFinalizable,所以 <code>.dividedBy(2).priority(100)</code> 这一部分即便不写,这条语句在语法上也已经完成。

做个总结:到这里我们发现 ConstraintMaker 以及和它相关的类,构造了一套 DSL 来让我们可以轻松地写出约束语句,而这些语句把信息都放到了一个 ConstraintDescription 实例(<code>self.description</code>)里面,但我们仍然不知道它是如何以 UIKit 里面的 NSLayoutConstraint 的形式作用的。

snp 是什么

SnapKit 里面存在这样一些东西:
<code>public protocol ConstraintDSL {}</code>
<code>public protocol ConstraintBasicAttributesDSL : ConstraintDSL {}</code>
<code>public protocol ConstraintAttributesDSL : ConstraintBasicAttributesDSL {}</code>
<code>public struct ConstraintViewDSL: ConstraintAttributesDSL {}</code>

上面我们知道了 <code>aView</code> 作为一个 UIView,它同时也就是一个 ConstraintView,ConstraintView 有一个 snp 的属性,这给我们提供了入口来通过 SnapKit 给任意的 UIView 或 AppKit 里面的 NSView 通过 <code>.snp</code> 这样的语法来写约束。

这个 snp 属性的类型就是结构体 ConstraintViewDSL

一看就是面向协议的写法,通过一个个的 extension 来给 protocol 添加功能,最后用 struct 实现出来,就有了 snp 这个属性。

let topView = UIView()
let centerView = UIView()
centerView.snp.makeConstraints({ make in
    make.top.equalTo(topView.snp.bottom).offset(16)
})

这段代码展现了 snp 的两个作用:

  1. snp 有 left top right bottom edges size 等一大堆属性,这些属性的类型是 ConstraintItem,这是用于构造约束位置关系的


  2. snp 作为 ConstraintViewDSL,有 <code>prepareConstraints</code> <code>makeConstraints</code> <code>remakeConstraints</code> <code>updateConstraints</code> <code>removeConstraints</code> 等函数,我们最常用的是 <code>makeConstraints</code> ,传入一个 closure,在里面写约束关系。这里要注意,我们使用的 <code>makeConstraints</code> 方法来源于 ConstraintViewDSL,但真正实现了构造约束的其实是我们上文里面写的 ConstraintMaker 里面的 <code>makeConstraints</code> 方法,见图:


约束是如何作用的

到现在我们还是没说,从 snp 到 ConstraintMaker,再到 ConstraintMakerFinalizable 的 description 属性,到底哪里创建了 NSLayoutConstraint,答案其实在之前提过多次的 ConstraintMaker 里面

// public class ConstraintMaker

internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
    let maker = ConstraintMaker(item: item)
    closure(maker)
    var constraints: [Constraint] = []
    for description in maker.descriptions {
        guard let constraint = description.constraint else {
            continue
        }
        constraints.append(constraint)
    }
    for constraint in constraints {
        constraint.activateIfNeeded(updatingExisting: false)
    }
}

internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
    guard item.constraints.count > 0 else {
        self.makeConstraints(item: item, closure: closure)
        return
    }
    
    let maker = ConstraintMaker(item: item)
    closure(maker)
    var constraints: [Constraint] = []
    for description in maker.descriptions {
        guard let constraint = description.constraint else {
            continue
        }
        constraints.append(constraint)
    }
    for constraint in constraints {
        constraint.activateIfNeeded(updatingExisting: true)
    }
}

我们传入一个闭包来写约束关系时,这个闭包给叫做 maker 的 ConstraintMaker 实例写入了信息,遍历 maker 的 descriptions 之后(我们之前说一条约束语句最终得到一个 self.description,但往往会有多条约束,所以 ConstraintMakerFinalizable 里面的 self.description,在 ConstraintMaker 里被一个数组维护),我们得到了 Constraint 数组。



Constraint 这个类还没有介绍过,不过上面这个核心方法加上以前的内容,已经可以让我们猜出来,约束是怎么写出来的了:


其他内容补充 1


随便写了两句,展示一下各个方法传入的参数的类型,发现有各种 Target,貌似很复杂,不过点开之后发现是这种景象:



说白了就是因为 <code>equalTo:</code> 这个方法里面能传的参数类型比较多,手动来一个一个限制一下,我们看到 ConstraintRelatableTarget 这里可以放一些原生的可以代表数字的类型,外加四个自定义的 Constraint 类型。其他的 Target 协议也差不多是这种情况。

个人觉得这种做法还是挺值得学习的。

其他内容补充 2

SnapKit 里面用来表示位置主体的类其实不是 ConstraintView,而是 ConstraintItem
我们管这个“主体”叫 target,一个 target,再加上一个 ConstraintAttributes 实例,就可以组成一个 ConstraintItem。


有 attributes 属性很好理解,因为比如我们去做对齐,可以是 aView 的 top 和 bView 的 bottom 对齐,而不能是 aView 和 bView 对齐。但是为什么 target 的类型是 AnyObject 而不是 ConstraintView,即 UIView 或 NSView 呢?

在 ConstraintViewDSL 里面,target 确实是 ConstraintView 类型,
但在 ConstraintLayoutSupportDSL 里面,target 是 ConstraintLayoutSupport 类型,
在 ConstraintLayoutGuideDSL 里面,target 是 ConstraintLayoutGuide 类型

这部分就不具体解释了,想一探究竟的去看 LayoutConstraintItem.swift 这个文件吧。

目录
相关文章
|
17天前
|
编解码 iOS开发 开发者
探索iOS开发中的SwiftUI框架
【5月更文挑战第31天】本文将深入探讨SwiftUI框架,这是Apple为iOS应用开发推出的最新用户界面工具包。我们将分析其核心概念、优势以及如何利用SwiftUI简化和加速开发流程,同时也会触及一些常见的挑战和解决方案。
|
1月前
|
前端开发 Android开发 iOS开发
【Flutter前端技术开发专栏】Flutter在Android与iOS上的性能对比
【4月更文挑战第30天】Flutter 框架实现跨平台移动应用,通过一致的 UI 渲染(Skia 引擎)、热重载功能和响应式框架提高开发效率和用户体验。然而,Android 和 iOS 的系统差异、渲染机制及编译过程影响性能。性能对比显示,iOS 可能因硬件优化提供更流畅体验,而 Android 更具灵活性和广泛硬件支持。开发者可采用代码、资源优化和特定平台优化策略,利用性能分析工具提升应用性能。
【Flutter前端技术开发专栏】Flutter在Android与iOS上的性能对比
|
2天前
|
安全 Android开发 iOS开发
探索Android与iOS开发的差异:平台特性与用户体验的对比分析
在移动应用开发的广阔天地中,Android和iOS两大阵营各据一方。本文将深入探讨这两个操作系统在开发环境、编程语言、用户界面设计及市场分布等方面的主要区别。通过比较分析,我们将揭示各自平台的特有优势,并讨论如何根据目标受众和业务需求选择适合的开发平台。
|
2天前
|
iOS开发 开发者
探索iOS开发中的SwiftUI框架
【6月更文挑战第14天】本文将深入探讨iOS开发领域的新星——SwiftUI框架。我们将从其设计理念出发,逐步解析其结构与核心组件,并通过实例展示如何利用SwiftUI简化界面构建流程,提升开发效率。同时,我们也将讨论SwiftUI在现有项目中的集成策略及其对iOS应用开发未来的可能影响。
8 1
|
3天前
|
安全 Java Android开发
探索Android与iOS开发的差异与挑战
在移动应用开发的广阔天地里,Android和iOS两大平台各自占据半壁江山。本文将深入探讨这两个平台的开发环境、工具、语言以及设计理念的差异,并分析这些差异给开发者带来的挑战。我们将从多个角度出发,包括用户界面设计、性能优化、安全性考量、以及市场分布等方面,为读者提供一个全面的视角,以理解在这两个平台上进行开发时需要考虑的关键因素。
|
3天前
|
Swift iOS开发 开发者
探索iOS开发中的SwiftUI框架
【6月更文挑战第13天】本文将深入探讨iOS开发中的一个重要工具——SwiftUI框架。我们将了解其基本概念,如何在实际项目中应用,以及它为开发者带来的优势和挑战。
|
5天前
|
iOS开发 开发者 UED
探索iOS开发中的SwiftUI框架
在移动应用开发的广阔天地中,苹果公司的SwiftUI框架以其声明式语法和直观布局管理,为iOS开发者带来了新的生产力工具。本文将深入探讨SwiftUI的设计哲学、核心概念以及在实际项目中如何高效运用该框架,旨在为读者提供一份全面的SwiftUI使用指南。
|
5天前
|
API Swift iOS开发
探索iOS开发中的SwiftUI框架
【6月更文挑战第11天】本文将深入探讨iOS开发中的一个重要工具——SwiftUI框架。我们将了解其基本概念,如何在实际项目中应用,以及它如何改变iOS应用的开发方式。
|
6天前
|
编解码 安全 Android开发
探索iOS与Android开发的差异:从界面到性能
【6月更文挑战第10天】在移动应用开发的广阔天地中,iOS和Android两大平台各占山头,它们在设计理念、用户体验、性能优化等方面展现出独特的魅力。本文将深入探讨这两大系统在开发过程中的主要差异,从用户界面设计到性能调优,揭示各自背后的技术逻辑与创新策略,为开发者提供全面的视角和实用的开发指南。
|
6天前
|
Android开发 Swift iOS开发
探索安卓与iOS开发的差异性
【6月更文挑战第9天】本文深入探讨了安卓和iOS这两大主流移动操作系统在应用程序开发方面的关键差异。从编程语言、用户界面设计到市场策略,我们将逐一分析这些差异如何影响开发者的选择和最终产品的用户体验。通过比较,我们旨在为开发者提供一份实用的指南,帮助他们在这两个平台上做出更明智的开发决策。