Swift Automatic Layout Framework-snapkit

Source: Internet
Author: User
Tags install cocoapods

Official website: 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 is easy To read and understand.
    • Type Safe by design to reduce programmer error and keep invalid constraints from being created on the first place for Maxi mized productivity.
    • Compatible for both IOS and OS X apps installable through Cocoapods or Carthage.
    • 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 is considered legacy platforms so you must manually integrate the SOU RCE files directly. Please see the Legacy platforms page for more information and steps.

Installing

The first thing you'll need to does with Snapkit are 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 this 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 foll Owing command:
$ git submodule add https://github.com/SnapKit/SnapKit.git
    • Open SnapKit the folder, and drag into the SnapKit.xcodeproj file navigator of your app project.
    • In Xcode, navigate to the Target Configuration window is clicking on the Blue Project icon, and selecting the application Target under the "Targets" heading in the sidebar.
    • Ensure the deployment target of matches that's the SnapKit.framework 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 in 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 add SnapKit.framework .
Usage

Snapkit is designed to being extremely easy to use. Let's say we want to layout a box that's 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 are also taking care of a few Crucia L 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 is called on all setTranslatesAutoresizingMaskIntoConstraints(false) appropriate views.
Not all things is created equal

.equalToEquivalent to Nslayoutrelation.equal

.lessThanOrEqualToEquivalent to Nslayoutrelation.lessthanorequal

.greaterThanOrEqualToEquivalent 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)

Viewattribute Nslayoutattribute
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 being greater than or equal to Label.left:2. Uiview/nsview
These constraints is exactly the Samemake.left.greaterThanOrEqualTo (label) Make.left.greaterThanOrEqualTo ( Label.snp_left)

  

3. Strict Checks

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

Width >= && width <= 400make.width.greaterthanorequalto ($) make.width.lessThanOrEqualTo (400)

  

However Auto Layout does not allow alignment attributes such as left, right, CenterY etc to is set to constant values. So if you pass a primitive for these attributes Snapkit would turn these into constraints relative to the view ' s Superview Ie:

Creates view.left <= View.superview.left + 10make.left.lessthanorequalto (10)

  

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

Make.top.equalTo (Make.height.equalTo) Make.size.equalTo (Cgsizemake (+)) Make.edges.equalTo ( Uiedgeinsetsmake (0, 0)) Make.left.equalTo (view). Offset (Uiedgeinsetsmake (10, 0, 10, 0))

  

Learn to Prioritize

.prorityAllows you to specify a exact priority

.priorityHighEquivalent to Uilayoutpriority.defaulthigh

.priorityMediumis half-between

.priorityLowEquivalent to Uilayoutpriority.defaultlow

Priorities is can 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 view2make.edges.equalTo (VIEW2);/Make top = Superview.top + 5, left = Superview.le FT + 10,//      bottom = superview.bottom-15, right = Superview.right-20make.edges.equalto (Superview). Inset (Uiedgeinse Tsmake (5, 10, 15, 20))

  

Size
Make width and height greater than or equal to TitleLabelmake.size.greaterThanOrEqualTo (Titlelabel)/Make width = Supe Rview.width +, height = Superview.height-50make.size.equalto (superview). Offset (Cgsizemake (100,-50))

  

Center
Make CenterX and CenterY = Button1make.center.equalTo (button1)//Make CenterX = superview.centerx-5, CenterY = Superv Iew.centery + 10make.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 Superviewmake.left.right.bottom.equalTo (Superview) make.top.equalTo (oth Erview)

  

Dear Life

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

1. References

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

var topconstraint:constraint? = nil...//when making constraintsview1.snp_makeconstraints {(make), Void in  self.topconstraint = Make.top.equa LTo (Superview). Offset (padding.top). Constraint  make.left.equalTo (superview). Offset (padding.left)}...//Then Later you can Callself.topConstraint.uninstall ()//or if you want to update the Constraintself.topConstraint.updateOffset (5)

  

2. snp_updateconstraints

Alternative if you is only updating the constant value of the constraint you can use the method snp_updateConstraints instead ofsnp_makeConstraints

This is Apple's recommended place for Adding/updating constraints//This method can get called multiple times in Respon  SE to setneedsupdateconstraints//which can is called by UIKit internally or in your code if you need to trigger an update To your constraintsoverride 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 is called at end of Method     super.updateconstraints ()}

  

3. snp_remakeconstraints

snp_remakeConstraintssnp_makeConstraintsis similar to, but would 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 (Ten)    } 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 a string or dictionary based and you get the strictest compile time checks possible.
Todo
    • Example Projects
    • Better Debugging support

Swift Automatic Layout Framework-snapkit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.