SnapKit使用示例


Github

官方文檔

安裝SnapKit

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

target '<Your Target Name>' do
    pod 'SnapKit', '~> 3.2.0'
end

入門示例

import UIKit
import SnapKit

class ViewController: UIViewController {
    
    lazy var box = UIView()
    override func viewDidLoad() {
        super.viewDidLoad()
        //在屏幕中間設(shè)置個110正方形  
        box.backgroundColor = UIColor.green
        self.view.addSubview(box)
        box.snp.makeConstraints{ (make) -> Void in
            make.width.height.equalTo(110)
            make.center.equalTo(self.view)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

image.png

NSLayoutAttributeCenterX 視圖的中點的X值
NSLayoutAttributeCenterY 視圖中點的Y值
NSLayoutAttributeBaseline 視圖的基準(zhǔn)線


  • 修正約束語法:
.equalTo:等于
.lessThanOrEqualTo:小于等于
.greaterThanOrEqualTo:大于等于

  • 倍率修正, 使用multipliedBy實例:
    override func viewDidLoad() {
        super.viewDidLoad()
    
        var box = UIView()
        box.backgroundColor = UIColor.green
        self.view.addSubview(box)
        box.snp.makeConstraints{ (make) -> Void in
            make.width.height.equalTo(110)
            make.center.equalTo(self.view)
        }
        
        var two = UILabel()
        two.backgroundColor = UIColor.yellow
        self.view.addSubview(two)
        //使two控件為box控件的0.3倍大小
        two.snp.makeConstraints{ (make) in
            make.center.equalTo(box)
            make.size.equalTo(box).multipliedBy(0.3)
        }

    }
        actionBut.snp.makeConstraints{ (make) in
//actionBut 與orangeBox偏移30            make.top.equalTo(orangeBox.snp.bottom).offset(30)
            make.width.equalTo(220)
            make.height.equalTo(35)
            make.centerX.equalTo(self.view)
        }
image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容