Swift語法糖---初始化Then

Then是一個swift初始化庫,只有80幾行的代碼庫,確可以讓初始化變得很優(yōu)雅

  • 使用then初始化AnyObject,這里以初始化控件為例
    lazy var label = UILabel().then({
        $0.text = "label"
        $0.textColor = .blue
    })
    let redView = UIView().then { (make) in
        make.backgroundColor = .red
        make.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
    }
    let button = UIButton().then ({
            $0.setTitle("點我", for: .normal)
            $0.setTitleColor(.red, for: .normal)
        })
  • 如果布局這樣還不簡單那就只能來騷的了,ThenSnapKit一起使用的方式
    let button1 = UIButton().then { (make) in
            make.setTitle("登錄", for: .normal)
            make.setTitleColor(.black, for: .normal)
            view.addSubview(make)
            
            make.snp.makeConstraints({ (make) in
                make.top.left.right.equalTo(0)
                make.height.equalTo(100)
            })
        }
  • 或者你還可以這樣
    let button2 = UIButton().then({
        $0.setTitle("登錄", for: .normal)
        $0.setTitleColor(.black, for: .normal)
        view.addSubview($0)
        
        $0.snp.makeConstraints({
            $0.top.equalTo(button1.snp.bottom)
            $0.left.right.equalTo(0)
            $0.height.equalTo(50)
        })
      })
  • 其他用法
    let newFrame = oldFrame.with {
          $0.size.width = 200
          $0.size.height = 100
    }
    newFrame.width // 200
    newFrame.height // 100
    UserDefaults.standard.do {
        $0.set("devxoul", forKey: "username")
        $0.set("devxoul@gmail.com", forKey: "email")
        $0.synchronize()
    }

Then: Github

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容