本文主要是介绍runtime 替换系统 imageNamed 方法,同时适配iphone和ipad图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
创建 UIImage 分类
UIImage+Category.h
#import <UIKit/UIKit.h>#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)#define IS_PAD (UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPad)NS_ASSUME_NONNULL_BEGIN@interface UIImage (Category)@endNS_ASSUME_NONNULL_END
UIImage+Category.m 文件
#import "UIImage+Category.h"#import <objc/runtime.h>@implementation UIImage (Category)+(void)load {Method imageNamed = class_getClassMethod(self,@selector(imageNamed:));Method mkeImageNamed =class_getClassMethod(self,@selector(mke_imageNamed:));method_exchangeImplementations(imageNamed, mkeImageNamed);}
+(instancetype)mke_imageNamed:(NSString*)name{
// UIImage * image;if( IS_IPHONE ){// iphone处理UIImage * image = [self mke_imageNamed:name];if (image != nil) {return image;}else {return nil;}} else {// ipad处理UIImage *image = [self mke_imageNamed:[NSString stringWithFormat:@"%@_ipad",name]];if (image != nil) {return image;}else {image = [self mke_imageNamed:name];return image;}}
使用:
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
imageview.image = [UIImage imageNamed:@"icon"];
这篇关于runtime 替换系统 imageNamed 方法,同时适配iphone和ipad图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!