Swift構文糖---初期化Then

1869 ワード

Thenはswift初期化ライブラリで、80数行のコードライブラリしかなく、初期化を優雅にすることができます.
  • 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("[email protected]", forKey: "email")
            $0.synchronize()
        }
    

    Then: Github