带有Lottie动画的动态按钮

时间:2020-03-14 13:07:45

标签: ios swift animation uibutton

我有一个简单的UIButton和一个title

let signUpButton: CustomButton = {
    let v = CustomButton(type: .system)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.setTitle("Registrieren", for: .normal)
    v.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
    v.titleLabel?.textColor = .white
    v.setTitleColor(.white, for: .normal)
    v.backgroundColor = UIColor.darkGray
    v.layer.cornerRadius = 3
    v.addTarget(self, action: #selector(signUpButtonTapped(_:)), for: .touchUpInside)
    return v
}()

现在我的目标是,当点击按钮时,title消失,button不再可单击,而应该显示loading-animation(Lottie)。 点击后有两个选项:

  1. 一切都很好,正在检索数据,我presentViewController
  2. 发生了一些错误,loading-animation消失了,title再次显示了

这是我到目前为止的buttonTapped功能(为简单起见,不完整的功能):

@objc func signUpButtonTapped(_ sender: Any) {

    let logoAnimation = AnimationView(name: "LoadingAnimation")
    logoAnimation.contentMode = .scaleAspectFit
    logoAnimation.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(logoAnimation)

    logoAnimation.centerXAnchor.constraint(equalTo: signUpButton.centerXAnchor).isActive = true
    logoAnimation.centerYAnchor.constraint(equalTo: signUpButton.centerYAnchor).isActive = true
    logoAnimation.heightAnchor.constraint(equalToConstant: 50).isActive = true
    logoAnimation.widthAnchor.constraint(equalToConstant: 50).isActive = true
    logoAnimation.loopMode = .loop
    logoAnimation.play()

    if error!= nil {
      logoAnimation.stop()
      logoAnimation.removeFromSuperView()
    } else {
          /* present new VC */ 
    }

现在,实际的问题是,如何使title出现/消失,我该怎么办?button在“加载”时不可点击?

我考虑过要创建一个与按钮的大小/颜色完全相同的UIView,并将其放置在button的顶部,但这似乎不是很干净和聪明。.

是否有快速简便的方法来完成此任务? 感谢您的帮助:)如果您需要更多详细信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

您可以执行此操作以隐藏按钮

btn.setTitle("", for: .normal)

btn.isHidden = true