How to show gif into UIImageView in Swift?

2019-01-23 20:37发布

I want use a gif in UIImageView, but I can't. My code is:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"gif"];
    UIImage *testImage = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];
    self.dataImageView.animationImages = testImage.images;
    self.dataImageView.animationDuration = testImage.duration;
    self.dataImageView.animationRepeatCount = 1;
    self.dataImageView.image = testImage.images.lastObject;
    [self.dataImageView startAnimating];
}

Swift:

var url : NSURL = NSBundle.mainBundle().URLForResource("MAES", withExtension: "gif")

In objective C I had animatedImageWithAnimatedGIFData but in swift I don't know how call this or if not exists..

Thanks!

1条回答
家丑人穷心不美
2楼-- · 2019-01-23 21:20

I assume you're using https://github.com/mayoff/uiimage-from-animated-gif for +UIImage animatedImageWithAnimatedGIFData: and the source code is in Objective-C.

You'll need to first import your Objective-C headers into Swift. Using Swift with Cocoa and Objective-C explains how to do this:

To import a set of Objective-C files in the same framework target as your Swift code, you’ll need to import those files into the Objective-C umbrella header for the framework.

To import Objective-C code into Swift from the same framework

  1. Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes.
  2. In your umbrella header file, import every Objective-C header you want to expose to Swift. For example:

    #import "UIImage+animatedGIF.h"

You can then setup your testImage as follows:

var testImage = UIImage.animatedImageWithAnimatedGIFData(
    NSData.dataWithContentsOfURL(url))
self.dataImageView.animationImages = testImage.images
self.dataImageView.animationDuration = testImage.duration
self.dataImageView.animationRepeatCount = 1
self.dataImageView.image = testImage.images.lastObject
self.dataImageView.startAnimating()
查看更多
登录 后发表回答