2015-09-04 156 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是示例項目。