Swift 語法糖then


then是一個swift初始化庫,只有80幾行的代碼庫,確可以讓初始化變得很優雅。

1.使用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)
        })

 

2.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)
        })
      })

 

3.其他用法

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()
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM