iOS 14 YYAnimatedImageView加载图片失败的原因主要是:iOS 14下UIKit
对 displayLayer:
的处理机制有所变化。displayLayer:
是CALayerDelegate
的代理方法。在iOS 14之前,UIKit
在调用这个方法之前就会去渲染UIImageView.image
。
而在iOS 14,UIKit
则是先去调用代理方法,如果你实现了displayLayer:
这个方法,那么UIKit
就不会再去渲染了。
解决办法
方法一
- (void)displayLayer:(CALayer *)layer {
UIImage *currentFrame = _curFrame;
if (currentFrame) {
layer.contentsScale = currentFrame.scale;
layer.contents = (__bridge id)currentFrame.CGImage;
} else {
// If we have no animation frames, call super implementation. iOS 14+ UIImageView use this delegate method for rendering.
if ([UIImageView instancesRespondToSelector:@selector(displayLayer:)]) {
[super displayLayer:layer];
}
}
// if (_curFrame) {
// layer.contents = (__bridge id)_curFrame.CGImage;
// }
}
方法二
#import "YYAnimatedImageView+iOS14.h"
#import <objc/runtime.h>
@implementation YYAnimatedImageView (iOS14)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method method1;
Method method2;
method1 = class_getInstanceMethod([self class], @selector(lz_displayLayer:));
method2 = class_getInstanceMethod([self class], @selector(displayLayer:));
method_exchangeImplementations(method1, method2);
});
}
- (void)lz_displayLayer:(CALayer *)layer {
Ivar ivar = class_getInstanceVariable(self.class, "_curFrame");
UIImage *_curFrame = object_getIvar(self, ivar);
if (_curFrame) {
layer.contents = (__bridge id)_curFrame.CGImage;
}else{
if (@available(iOS 14.0, *)) {
[super displayLayer:layer];
}
}
}
@end