欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-31 17:17:37
...

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

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下的约束动画(一)

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

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