ios:条件绑定的初始化程序必须具有Optional类型,而不是'LOTAnimationView'

时间:2018-05-16 11:22:37

标签: ios animation lottie

我不断收到此错误:条件绑定的初始化程序必须具有可选类型,而不是'LOTAnimationView' 在如果让animationView = LOTAnimationView(名称:“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()
    }}

2 个答案:

答案 0 :(得分:1)

只需从代码中删除if let即可。要使用if,您必须拥有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 if this。

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
}

答案 1 :(得分:0)

//测试

         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()

     }