Reputation: 1306
I've been trying to animate a GIF in Swift but it just doesn't work. I think I found a way but there's an error, please help.
Here's the code:
@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.
// ...
}
Upvotes: 0
Views: 9121
Reputation: 71854
I have created one example for you.
Here is code:
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()
}
}
You can see Result HERE.
And HERE is sample project.
Upvotes: 0
Reputation: 2294
You may run gif files directly, follow the links below;
https://github.com/kaishin/gifu
How to load GIF image in Swift?
As far as the issue in you code is, as already 'Leo Dabus' pointed out, is you are not un-wrapping the UIImage instances. Try same code with the following modifications.
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()
Upvotes: 1
Reputation: 236285
You just need to unwrap the optional UIImage returned by UIImage(named:) method. Try like this:
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.
}
}
Upvotes: 0