如何在Swift中将gif显示到UIImageView中?

use*_*888 5 animation gif swift ios8

我想在UIImageView中使用gif,但我不能.我的代码是:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

迅速:

var url : NSURL = NSBundle.mainBundle().URLForResource("MAES", withExtension: "gif")
Run Code Online (Sandbox Code Playgroud)

在目标CI中有animatedImageWithAnimatedGIFData,但在swift中我不知道如何调用此或如果不存在..

谢谢!

Mar*_*uro 12

我假设你使用的是https://github.com/mayoff/uiimage-from-animated-gif,+UIImage animatedImageWithAnimatedGIFData:源代码在Objective-C中.

您需要先将Objective-C标头导入Swift.使用Swift与Cocoa和Objective-C解释了如何执行此操作:

要在与Swift代码相同的框架目标中导入一组Objective-C文件,您需要将这些文件导入到框架的Objective-C伞形标题中.

从同一框架将Objective-C代码导入Swift

  1. 在"构建设置"下的"打包"中,确保将该框架目标的"定义模块"设置设置为"是".
  2. 在您的伞头文件中,导入要向Swift公开的每个Objective-C头.例如:

    #import "UIImage+animatedGIF.h"

然后,您可以testImage按如下方式设置:

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()
Run Code Online (Sandbox Code Playgroud)