如何在 Swift 中将 gif 显示到 UIImageView 中? [英] How to show gif into UIImageView in Swift?

查看:34
本文介绍了如何在 Swift 中将 gif 显示到 UIImageView 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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];
}

斯威夫特:

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

在目标 C 中,我有 animationImageWithAnimatedGIFData 但很快我不知道如何调用它或者如果不存在..

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

谢谢!

推荐答案

我假设您正在使用 https://github.com/mayoff/uiimage-from-animated-gif for +UIImage animationImageWithAnimatedGIFData:,源代码在Objective-C中.

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

您需要先将 Objective-C 头文件导入 Swift.将 Swift 与 Cocoa 和 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:

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

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.

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

  1. 在构建设置下的打包中,确保该框架目标的定义模块设置设为是.
  2. 在你的伞头文件中,导入你想要暴露给 Swift 的每个 Objective-C 头文件.例如:

  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"

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

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()

这篇关于如何在 Swift 中将 gif 显示到 UIImageView 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆