美文网首页
runtime 交换UIImage imageNamed 方法

runtime 交换UIImage imageNamed 方法

作者: 白色天空729 | 来源:发表于2019-04-22 11:03 被阅读0次

    1.新建UIimage 分类show.
    UIImage+Show.h

    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface UIImage (Show)
    
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    

    UIImage+Show.m

    #import "UIImage+Show.h"
    #import <objc/runtime.h>
    
    @implementation UIImage (Show)
    
    + (void)load {
        NSString *className = NSStringFromClass(self.class);
        NSLog(@"classname %@", className);
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            //要特别注意你替换的方法到底是哪个性质的方法
            // When swizzling a Instance method, use the following:
            //        Class class = [self class];
            
            // When swizzling a class method, use the following:
            Class class = object_getClass((id)self);
            
            SEL originalSelector = @selector(imageNamed:);
            SEL swizzledSelector = @selector(zdx_imagedNamed:);
            
            Method originalMethod = class_getInstanceMethod(class, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
            
            BOOL didAddMethod =
            class_addMethod(class,
                            originalSelector,
                            method_getImplementation(swizzledMethod),
                            method_getTypeEncoding(swizzledMethod));
            
            if (didAddMethod) {
                class_replaceMethod(class,
                                    swizzledSelector,
                                    method_getImplementation(originalMethod),
                                    method_getTypeEncoding(originalMethod));
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod);
            }
        });
    }
    
    +(UIImage*)zdx_imagedNamed:(NSString *)name {
        NSMutableString *mutaleStr = name.mutableCopy;
        [mutaleStr appendString:@"_obj"];
        NSLog(@"拼接的字符串%@",mutaleStr);
        UIImage *image = [UIImage zdx_imagedNamed:mutaleStr];
        
        
        if (image) {
            NSLog(@"runtime 添加额外功能成功--加载成功");
        } else {
            NSLog(@"runtime 添加额外功能成功--加载失败");
        }
        return image;
    }
    
    @end
    
    

    调用:

    _imgView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.view addSubview:_imgView];
        _imgView.image = [UIImage imageNamed:@"testImg"];
    

    控制器打印:

    2019-04-22 10:56:44.665 TestSwizDemo[5999:117295] 拼接的字符串testImg_obj
    2019-04-22 10:56:44.666 TestSwizDemo[5999:117295] runtime 添加额外功能成功--加载失败
    

    相关文章

      网友评论

          本文标题:runtime 交换UIImage imageNamed 方法

          本文链接:https://www.haomeiwen.com/subject/pftygqtx.html