Swift

Swift Then语法糖使用教程

2021-08-03  本文已影响0人  JianLee

简介

Then是一个Swift初始化库,使用非常简洁和优雅,大大提高代码可阅读性。

开始使用

依赖

  pod 'Then'

切换到项目目录,执行

  pod install

1.使用Then初始化控件,并设置属性

例1

    lazy var label = UILabel().then({
            $0.text = "label"
            $0.textColor = .blue
        })
例1.jpg

例2

    let redView = UIView().then { (make) in
            make.backgroundColor = .red
            make.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
        }
例2.jpg

例3

    let redBtn = UIButton().then{(make) in
        make.setTitle("点我", for: .normal)
        make.setTitleColor(.red, for: .normal)
        make.backgroundColor = UIColor.yellow
    }
例3.jpg

例4

    let blueBtn = UIButton().then(
        {
            $0.setTitle("点我", for: .normal)
            $0.setTitleColor(.blue, for: .normal)
            $0.backgroundColor = UIColor.yellow
        }
    )
例4.jpg

添加到视图中展示

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(label)
        label.snp.makeConstraints{(make) in
            make.width.equalTo(80)
            make.height.equalTo(40)
            make.center.equalToSuperview()
        }   
    }

2.Then和SnapKit一起使用的方式

    override func viewDidLoad() {
        super.viewDidLoad()
        let blakBtn=UIButton().then(
            {
                $0.setTitle("点我", for: .normal)
                $0.setTitleColor(.white, for: .normal)
                $0.backgroundColor = UIColor.black
            view.addSubview($0)
                $0.snp.makeConstraints{(make) in
                    make.width.equalTo(80)
                    make.height.equalTo(40)
                    make.center.equalToSuperview()
                }
        })
    }
例5.jpg

还有一些其它用法 可以参照官方例子Then

上一篇 下一篇

猜你喜欢

热点阅读