1

I am trying to animate a gif in Swift Playgrounds. I have my code below.

let image = UIImage(named: "earth.gif")
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.size.width - 40, height: 150.0)
self.view?.addSubview(imageView)

Any ideas on why this isn't working?

Thank You

Psonthalia
  • 179
  • 1
  • 12
  • Try checking this SO question and see if anything in here helps: http://stackoverflow.com/questions/24069479/swift-playgrounds-with-uiimage – nviens Mar 17 '17 at 01:48
  • Unfortunately, that doesn't fix it. – Psonthalia Mar 17 '17 at 02:00
  • What problems are you running into? Does is throw errors for the last 3 lines? – nviens Mar 17 '17 at 02:03
  • The gif just shows as an image, it isn't animating. Sorry, I din't specify that – Psonthalia Mar 17 '17 at 02:04
  • Try taking a look here https://possiblemobile.com/2015/03/prototyping-uiview-animations-swift-playground/ for some ideas on using `animateWithDuration` on a `view` in the Swift Playground – nviens Mar 17 '17 at 02:16
  • You probably need to add `import PlaygroundSupport` and `PlaygroundPage.current.needsIndefiniteExecution = true` – Eric Aya Mar 17 '17 at 12:43

1 Answers1

0

UIImage does not support gif animation, but you can do this via 3rd party libraries or Extensions.

You can use the extension here SwiftGif

Add the linked file to the source of playground, then run your code like this:

import UIKit
import PlaygroundSupport



let image = UIImage.gif(name: "earth.gif")
.....
PlaygroundPage.current.liveView = imageView

However for macOS NSImage can be directly showed, you can create a mac playground and write code like this to directly see the animating gif

import Cocoa
import PlaygroundSupport


let image = NSImage(named: "earth.gif")
let imageView = NSImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 200.0, height: 200.0)
PlaygroundPage.current.liveView = imageView
XueYu
  • 2,355
  • 29
  • 33