SnapKit的使用 swift

下载链接

https://github.com/SnapKit/SnapKit

 

makeConstraints 制作约束

updateConstraints 修改约束

import UIKit
import SnapKit

class ViewController: UIViewController {

    lazy var blackView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        blackView.backgroundColor = UIColor.black
        view.addSubview(blackView)
        blackView.snp.makeConstraints { (make) in
            
            // 四个约束确定位置和大小
            make.width.equalTo(100)
            make.height.equalTo(150)
            make.top.equalTo(10)
            make.centerX.equalToSuperview()
        }
 
    }
    
    override func updateViewConstraints() {
        
        blackView.snp.updateConstraints { (make) in
            // 更新距离父视图顶部的约束(从 10 ---> 300 )
            make.top.equalTo(300)
        }
        
        // 根据苹果,调用父类应该放在末尾
        super.updateViewConstraints()
    }
}

 

remakeConstraints 重做约束

本质就是:去掉已有的所有约束, 重新做约束,下面的代码因为少了一个约束,会报错

// 点击更新/制作约束
func buttonAction() {
    
    // 注意这里是 remakeConstraints
    blackView.snp.remakeConstraints { (make) in
        make.width.height.equalTo(20)
        make.top.equalTo(300)
    }
    
    print("这里试试snapkit有没有报警告")
}

 

dividedBy 几等分,适合平分屏幕的几个按钮这种情况

class ViewController: UIViewController {
    
    lazy var redView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        redView.backgroundColor = UIColor.red
        view.addSubview(redView)
        redView.snp.makeConstraints { (make) in
            // width 是父视图宽的一半
            make.width.equalToSuperview().dividedBy(2)
            // height 是父视图高的三分之一
            make.height.equalToSuperview().dividedBy(3)
            make.center.equalToSuperview()
        }
        
    }
}

 

multipliedBy 几倍,适合图片宽高比这种情况

        coverView.snp.makeConstraints { make in
            make.top.equalTo(15.0)
            make.left.right.equalToSuperview()
            make.height.equalTo(coverView.snp.width).multipliedBy(210.0 / 168.0)
        }

 

safeAreaLayoutGuide 布局

class ViewController: UIViewController {
    
    lazy var magentaView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        magentaView.backgroundColor = .magenta
        view.addSubview(magentaView)
        magentaView.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        
    }
}

 

 

 

 

 

  • iPhone X之前, view.safeAreaLayoutGuide(即安全区域)的顶部距离当前窗口顶部一个状态栏的高度(20dp)

  • 对于iPhone X来说,view.safeAreaLayoutGuide(即安全区域)的顶部距离当前窗口顶部一个导航栏的高度(44dp)

  • iPhone X之前, view.safeAreaLayoutGuide(即安全区域)的底部距离就是当前窗口(当前视图)的底部

  • 对于iPhone X来说,view.safeAreaLayoutGuide(即安全区域)的底部距离当前窗口底部 34dp

 

 

posted @ 2022-06-24 11:32  黄增松  阅读(502)  评论(0编辑  收藏  举报