Swift 自動佈局框架-SnapKit

来源:http://www.cnblogs.com/xiaopin/archive/2016/09/01/5830577.html
-Advertisement-
Play Games

官方網址:http://snapkit.io/ Github: https://github.com/SnapKit/SnapKit SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. Simple & Expressive ...


官方網址:http://snapkit.io/

Github: https://github.com/SnapKit/SnapKit

SnapKit is a DSL to make Auto Layout easy on both iOS and OS X.

  • Simple & Expressive chaining DSL allows building constraints with minimal amounts of code while ensuring they are easy to read and understand.
  • Type Safe by design to reduce programmer error and keep invalid constraints from being created in the first place for maximized productivity.
  • Compatible for both iOS and OS X apps installable through Cocoapods or Carthage.
  • Free to use in all projects and licensed under the flexible MIT license.

Requirements

  • iOS 7.0+ / OS X 10.9+
  • Swift 2.0
  • Xcode 7.0+

While SnapKit supports iOS 7.0 and OS X 10.9 these are considered legacy platforms, so you must manually integrate the source files directly. Please see the Legacy Platforms page for more information and steps.

Installing

The first thing you’ll need to do with SnapKit is get it installed into your project. We support three different integrations:

Cocoapods

CocoaPods is a dependency manager for Cocoa projects.

CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:

$ gem install cocoapods

To integrate SnapKit into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'SnapKit', '~> 0.15.0'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate SnapKit into your Xcode project using Carthage, specify it in your Cartfile:

github "SnapKit/SnapKit" >= 0.15.0

Embedded Framework

  • Add SnapKit as a submodule by opening the Terminal, cd-ing into your top-level project directory, and entering the following command:
$ git submodule add https://github.com/SnapKit/SnapKit.git
  • Open the SnapKit folder, and drag SnapKit.xcodeproj into the file navigator of your app project.
  • In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
  • Ensure that the deployment target of SnapKit.framework matches that of the application target.
  • In the tab bar at the top of that window, open the "Build Phases" panel.
  • Expand the "Target Dependencies" group, and add SnapKit.framework.
  • Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and addSnapKit.framework.

Usage

SnapKit is designed to be extremely easy to use. Let's say we want to layout a box that is constrained to it's superview's edges with 20pts of padding.

let box = UIView()
superview.addSubview(box)

box.snp_makeConstraints { (make) -> Void in
    make.top.equalTo(superview).offset(20)
    make.left.equalTo(superview).offset(20)
    make.bottom.equalTo(superview).offset(-20)
    make.right.equalTo(superview).offset(-20)
}

Or even shorter:

let box = UIView()
superview.addSubview(box)

box.snp_makeConstraints { (make) -> Void in
    make.edges.equalTo(superview).inset(UIEdgeInsetsMake(20, 20, 20, 20))
}

Not only does this greatly shorten and increase the readability of constraints SnapKit is also taking care of a few crucial steps in the process:

  • Determining the best common superview to install the constraints on.
  • Keeping track of the constrainted installed so they can easily be removed later.
  • Ensuring setTranslatesAutoresizingMaskIntoConstraints(false) is called on all appropriate views.

Not all things are created equal

.equalTo equivalent to NSLayoutRelation.Equal

.lessThanOrEqualTo equivalent to NSLayoutRelation.LessThanOrEqual

.greaterThanOrEqualTo equivalent to NSLayoutRelation.GreaterThanOrEqual

These three equality constraints accept one argument which can be any of the following:

1. ViewAttribute

make.centerX.lessThanOrEqualTo(view2.snp_left) 
make.centerX.lessThanOrEqualTo(view2.snp_left)

ViewAttributeNSLayoutAttribute
view.snp_left NSLayoutAttribute.Left
view.snp_right NSLayoutAttribute.Right
view.snp_top NSLayoutAttribute.Top
view.snp_bottom NSLayoutAttribute.Bottom
view.snp_leading NSLayoutAttribute.Leading
view.snp_trailing NSLayoutAttribute.Trailing
view.snp_width NSLayoutAttribute.Width
view.snp_height NSLayoutAttribute.Height
view.snp_centerX NSLayoutAttribute.CenterX
view.snp_centerY NSLayoutAttribute.CenterY
view.snp_baseline NSLayoutAttribute.Baseline


if you want view.left to be greater than or equal to label.left:
2. UIView/NSView

// these two constraints are exactly the same
make.left.greaterThanOrEqualTo(label)
make.left.greaterThanOrEqualTo(label.snp_left)

  

3. Strict Checks

Auto Layout allows width and height to be set to constant values. if you want to set view to have a minimum and maximum width you could pass a primitive to the equality blocks:

// width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(200)
make.width.lessThanOrEqualTo(400)

  

However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. So if you pass a primitive for these attributes SnapKit will turn these into constraints relative to the view's superview ie:

// creates view.left <= view.superview.left + 10
make.left.lessThanOrEqualTo(10)

  

You can also use other primitives and structs to build your constraints, like so:

make.top.equalTo(42)
make.height.equalTo(20)
make.size.equalTo(CGSizeMake(50, 100))
make.edges.equalTo(UIEdgeInsetsMake(10, 0, 10, 0))
make.left.equalTo(view).offset(UIEdgeInsetsMake(10, 0, 10, 0))

  

Learn to prioritize

.prority allows you to specify an exact priority

.priorityHigh equivalent to UILayoutPriority.DefaultHigh

.priorityMedium is half way between high and low

.priorityLow equivalent to UILayoutPriority.DefaultLow

Priorities are can be tacked on to the end of a constraint chain like so:

make.left.greaterThanOrEqualTo(label.snp_left).priorityLow()
make.top.equalTo(label.snp_top).priority(600)

  

Composition, composition, composition

SnapKit also gives you a few convenience methods to create multiple constraints at the same time.

edges

// make top, left, bottom, right equal view2
make.edges.equalTo(view2);

// make top = superview.top + 5, left = superview.left + 10,
//      bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).inset(UIEdgeInsetsMake(5, 10, 15, 20))

  

size

// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel)

// make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).offset(CGSizeMake(100, -50))

  

center

// make centerX and centerY = button1
make.center.equalTo(button1)

// make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).offset(CGPointMake(-5, 10))

  

You can chain view attributes for increased readability:

// All edges but the top should equal those of the superview
make.left.right.bottom.equalTo(superview)
make.top.equalTo(otherView)

  

Hold on for dear life

Sometimes you need modify existing constraints in order to animate or remove/replace constraints. In SnapKit there are a few different approaches to updating constraints.

1. References

You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. You could also reference multiple constraints by storing them away in an array.

var topConstraint: Constraint? = nil

...

// when making constraints
view1.snp_makeConstraints { (make) -> Void in
  self.topConstraint = make.top.equalTo(superview).offset(padding.top).constraint
  make.left.equalTo(superview).offset(padding.left)
}

...
// then later you can call
self.topConstraint.uninstall()

// or if you want to update the constraint
self.topConstraint.updateOffset(5)

  

2. snp_updateConstraints

Alternative if you are only updating the constant value of the constraint you can use the methodsnp_updateConstraints instead of snp_makeConstraints

// this is Apple's recommended place for adding/updating constraints
// this method can get called multiple times in response to setNeedsUpdateConstraints
// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints
override func updateConstraints() {
    self.growingButton.snp_updateConstraints { (make) -> Void in
        make.center.equalTo(self);
        make.width.equalTo(self.buttonSize.width).priorityLow()
        make.height.equalTo(self.buttonSize.height).priorityLow()
        make.width.lessThanOrEqualTo(self)
        make.height.lessThanOrEqualTo(self)
    }

    // according to apple super should be called at end of method
     super.updateConstraints()
}

  

3. snp_remakeConstraints

snp_remakeConstraints is similar to snp_makeConstraints, but will first remove all existing constraints installed by SnapKit.

func changeButtonPosition() {
  self.button.snp_remakeConstraints { (make) -> Void in 
    make.size.equalTo(self.buttonSize)

    if topLeft {
      make.top.left.equalTo(10)
    } else {
      make.bottom.equalTo(self.view).offset(-10)
      make.right.equalTo(self.view).offset(-10)
    }
  }
}

  

Features

  • Not limited to a subset of Auto Layout. Anything NSLayoutConstraint can do SnapKit can also do.
  • Better debugging support to help find breaking constraints.
  • No crazy operator overloads.
  • Not string or dictionary based and you get the strictest compile time checks possible.

TODO

  • Example Projects
  • Better Debugging Support

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Drawable animation可以載入Drawable資源實現幀動畫。AnimationDrawable是實現Drawable animations的基本類。 這裡用AnimationDrawable 簡單模擬動態圖的實現。 fragment_main 佈局文件 只需要放一個 ImageVie ...
  • 草原上的兩匹馬! 打從當年微信開始佈局公眾號之初時,估計就已經想到了與支付寶正面衝突的場面,所以微信先來個瞞天過海,在春晚搞了個微信紅包,那叫一個火呀,此時的云云隱隱感覺到些許不安。 早期的微信開發者可能都知道,微信公眾號剛開始的時候接入支付要交巨額的保證金,根據行業不同,金額也不同,但也有大幾萬呢 ...
  • ...
  • 以前一直在用ListView,,,最近才看RecyclerView發現好強大。RecyclerView前提是Android版本在5.0以上,本人以前用的是eclipse只支持到4.4。索性就安裝一個Android Studio去開發RecyclerView吧 真是萬事開頭難,然後中間難,然後結尾難。 ...
  • Swift - 實現點擊cell動態修改高度 效果 源碼 https://github.com/YouXianMing/Swift-Animations ...
  • 補充一點遺漏的Xcode配置。 1.偏好設置。Xcode的菜單欄Xcode -> Preference Fonts & Colors可以自定義編碼區和控制台的背景、字體。 Text Editing:Line numbers顯示行數,Code folding ribbon使代碼可以摺疊,page gu ...
  • 1、項目地址 https://github.com/iamMehedi/Secured-Preference-Store 2、使用方法 2.1、存數據 2.2、 取數據 3、xml文件內容 可以看到xml文件裡面的內容都已經變成了混亂的字元,從而實現加密。 4、SecurePreferenceSto ...
  • 一:首先查看一下關於UITableViewCell重用的定義 在tableview新建的時候,會新建一個復用池(reuse pool).這個復用池可能是一個隊列,或者是一個鏈表,保存著當前的Cell.pool中的對象的復用標識符就是reuseIdentifier,標識著不同的種類的cell.所以調用 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...