2015-09-04 150 views
0

我一直试图在Swift中动画GIF,但它不起作用。我想我找到了一种方式,但有一个错误,请帮助。Swift中的动画GIF动画

下面的代码:

@IBOutlet var imageView: UIImageView! 
override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 
    // (Here is the error it states "Cannot assign a value of type '[UIImage?]' to a value of type '[UIImage]?'") 
    imageView.animationImages = [ 

     UIImage(named: "logo1.jpg"), 
     UIImage(named: "logo2.jpeg"), 
     UIImage(named: "logo3.png") 
    ] 

    imageView.animationDuration = 3 
    imageView.startAnimating() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
    // ... 
} 

回答

0

你只需要通过解开返回的UIImage可选的UIImage(名为:)方法。像这样尝试:

class ViewController: UIViewController { 
    @IBOutlet weak var imageView: UIImageView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     imageView.animationImages = [ 
      UIImage(named: "logo1")!, 
      UIImage(named: "logo2")!, 
      UIImage(named: "logo3")!] 

     imageView.animationDuration = 3 
     imageView.startAnimating() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
+0

这仍然不起作用,因为问题是imageView.animationImages –

+0

你能详细说明这个原因吗? –

+0

我不知道为什么 –

1

你可以直接运行gif文件,按照下面的链接;

https://github.com/kaishin/gifu

How to load GIF image in Swift?

至于在你的代码是问题,因为已经“狮子座Dabus”指出的那样,是你是不是未包裹的UIImage实例。尝试使用相同的代码进行以下修改。

imageView.animationImages = [ 

     UIImage(named: "logo1.jpg")!, //File Extension would not be required if .png 
     UIImage(named: "logo2.jpeg")!, //File Extension would not be required if .png 
     UIImage(named: "logo3.png")! 
    ] 

    imageView.animationDuration = 3 
    imageView.startAnimating() 
0

我已经为您创建了一个示例。

这里是代码:

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var imageView: UIImageView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     imageView.animationImages = [ 
      UIImage(named: "1")!, 
      UIImage(named: "2")!, 
      UIImage(named: "3")!, 
      UIImage(named: "4")!, 
      UIImage(named: "5")!, 
      UIImage(named: "6")!, 
      UIImage(named: "7")!, 
      UIImage(named: "8")!, 
      UIImage(named: "9")!, 
      UIImage(named: "10")!, 
      UIImage(named: "11")!, 
      UIImage(named: "12")! 

     ] 

     imageView.animationDuration = 3 
     imageView.startAnimating() 
    } 
} 

你可以看到结果HERE

HERE是示例项目。