【问题标题】:ios: Initializer for conditional binding must have Optional type, not 'LOTAnimationView'ios:条件绑定的初始化程序必须具有可选类型,而不是“LOTAnimationView”
【发布时间】:2018-05-16 11:22:36
【问题描述】:

我不断收到此错误:条件绑定的初始化程序必须具有可选类型,而不是“LOTAnimationView” 在 if let animationView = LOTAnimationView(name: "pop_heart") { 行代码上。我认为代码的格式可能是错误的。谁能指导我正确的方向?谢谢:)

override func viewDidLoad() {
    super.viewDidLoad()
    print("view loaded")

    if let animationView = LOTAnimationView(name: "pop_heart") {
        animationView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
        animationView.center = self.view.center
        animationView.contentMode = .scaleAspectFill
        animationView.loopAnimation = true
        animationView.animationSpeed = 0.5
        view.addSubview(animationView)

        animationView.play()
    }}

【问题讨论】:

  • 你的代码应该可以工作看看这个demo

标签: ios animation lottie


【解决方案1】:

只需从您的代码中删除 if let。要使用 if let,您必须有一个 Optional 变量。

override func viewDidLoad() {
    super.viewDidLoad()
    print("view loaded")

     animationView = LOTAnimationView(name: "pop_heart") 
     animationView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
     animationView.center = self.view.center
     animationView.contentMode = .scaleAspectFill
     animationView.loopAnimation = true
     animationView.animationSpeed = 0.5
     view.addSubview(animationView)
     animationView.play()
}

或者如果你想使用if let,你可以像这样使用。

if let value = someMethodWhichReturnsAny as? String {
    //In above like there is a method which returns a string but in the form of type `Any` so I downcast it to String with optional and remove the nil case with if let
}

【讨论】:

    【解决方案2】:

    //测试

             let backgroundAnimation: LOTAnimationView = {
                    let animationView = LOTAnimationView(name: "10173-success-lumina")
                 animationView.loopAnimation = true
                    animationView.contentMode = .scaleAspectFill
                    return animationView
                }()
    
             backgroundAnimation.frame = view.frame
             view.addSubview(backgroundAnimation)
             view.sendSubviewToBack(backgroundAnimation)
             backgroundAnimation.play()
    
         }
    

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2017-01-22
      • 2018-03-25
      • 2016-01-08
      • 2017-04-08
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多