Swift iOS : 使用Cartography佈局

RecoReco發表於2019-01-23

廣告

Swift iOS開發小書 ,幫你快速上手開發 www.ituring.com.cn/book/2413

正文

使用SnapKit佈局當然不錯,但是我覺得Cartography更好,因為可以寫出更加規整的佈局程式碼。表示式總是比起鏈式函式容易閱讀。

依然是佈局三個Label,我把兩種都寫出來做一個對比:

import SnapKit
import UIKit
import Cartography
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let page = Page()
        self.window!.rootViewController = page
        self.window?.makeKeyAndVisible()
        return true
    }
}
class Page: UIViewController {
    var count = 0
    var label1 : UILabel!
    var label2 : UILabel!
    var label3 : UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        label1   = UILabel()
        label1.backgroundColor = .red
        view.addSubview(label1)

        label2   = UILabel()
        label2.backgroundColor = .red
        view.addSubview(label2)

        label3   = UILabel()
        label3.backgroundColor = .red
        view.addSubview(label3)

        label1.text = "1111"
        label2.text = "2222"
        label3.text = "3333"
        setup_cartography()
    }
    func setup_cartography(){
        constrain(view,label1,label2,label3){
            $1.left == $0.left  + 5
            $1.top  == $0.top + 100
            //
            $2.left == $1.right + 10
            $2.top  == $1.top
            //
            $3.left == $1.left
            $3.top  == $1.bottom + 5
        }
    }
    func setup_snapx(){
        label1.snp.makeConstraints{
            $0.left.equalTo(view).offset(5);
            $0.top.equalTo(view).offset(100);
        }
        label2.snp.makeConstraints{
            $0.left.equalTo(label1.snp.right).offset(10);
            $0.top.equalTo(label1)
        }
        label3.snp.makeConstraints{
            $0.left.equalTo(label1)
            $0.top.equalTo(label1.snp.bottom).offset(5)
        }
    }
}複製程式碼

Cartography內宣告佈局的表示式中,使用到了“==”操作符,它並不是拿來做等值判斷的,而是宣告兩者恆等,是一個運算子的過載。運算子的過載用在這裡,真是很帥氣。學到了。

相關文章