Swift4.0 - Masonry下的约束动画(一)

Swift4.0 - Masonry下的约束动画(一)_第1张图片

import UIKit
import Masonry

class LFlunchView: UIView {

    ///MARK: lazy
    private lazy var bgImgView = UIImageView.init(image: UIImage.init(named: "ad_background"))
    private lazy var iconImgView = UIImageView.init(image: UIImage.init(named: "avatar_default_big"))
    private lazy var nameLab = UILabel.cz_label(withText: "用户昵称", fontSize: 15, color: UIColor.darkGray) ?? UILabel.init()
    private lazy var imgeViewBottomConstraint: MASConstraint? = MASConstraint.init()

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.frame = UIScreen.main.bounds
        createUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didMoveToWindow() {
        super.didMoveToWindow()

        self.layoutIfNeeded()
        addAnimationToUI()
    }
}


// MARK: - UI初始化布局
extension LFlunchView {


    /// 创建UI视图
    private func createUI() {
        self.addSubview(bgImgView)
        bgImgView.sizeToFit()

        self.addSubview(iconImgView)
        iconImgView.sizeToFit()

        self.addSubview(nameLab)
        nameLab.alpha = 0.1
        nameLab.sizeToFit()


        bgImgView.mas_makeConstraints { (make) in
            make?.center.mas_equalTo()(self)
            make?.size.mas_equalTo()(self.frame.size)
        }

        iconImgView.mas_makeConstraints { (make) in
            make?.centerX.equalTo()(self)
            self.imgeViewBottomConstraint = make?.bottom.equalTo()(self.mas_bottom)?.multipliedBy()(0.78)
        }

        nameLab.mas_makeConstraints { (make) in
            make?.centerX.equalTo()(self)
            make?.top.equalTo()(iconImgView.mas_bottom)?.offset()(20)
        }
    }


    /// 添加动画到UI
    private func addAnimationToUI(){

        //1. 告知需要更改约束
        self.setNeedsUpdateConstraints()

        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {

            self.imgeViewBottomConstraint?.equalTo()(-300)

            //2. 立即更新约束
            self.layoutIfNeeded()

        }) { (animationEnd) in

            UIView.animate(withDuration: 0.5, animations: {
                self.nameLab.alpha = 1
            })
        }
    }


}

这里要注意两点

  1. 动画添加在 didMoveToWindow()中, 需要主动调用 self.layoutIfNeed()

Swift4.0 - Masonry下的约束动画(一)_第2张图片

  1. Masonry动画执行,要这样设置,否则就无动画效果,直接变成新约束界面

Swift4.0 - Masonry下的约束动画(一)_第3张图片

你可能感兴趣的:(swift4.0,#,iOS,语法技巧)