美文网首页iOS Developer - RuntimeiOS Developer
Runtime(二) -- 项目实战篇

Runtime(二) -- 项目实战篇

作者: 横爬介士 | 来源:发表于2016-08-21 14:02 被阅读140次

    上篇主要是runtime的理论基础(地址请戳这里),但是具体到项目中的时候很少会想到使用runtime来解决问题,本文主要根据笔者在项目中的某些需求,将使用runtime的某些场景记录下来。

    1 修改UITextField中placeholder的颜色以及文字大小

    项目需求:textFiled为镂空显示父视图的背景色,placeholder的颜色为白色,切字体字号为22px

    1.1 解决问题思路

    查看UITextField的属性发现并没有相关设置的属性,使用runtime遍历UITextField的属性遍历,并通过次变量修改placeholder的颜色和字体大小.

     unsigned int count;
        Ivar *ivarList = class_copyIvarList([UITextField class], &count);
        
        for (int i = 0 ; i < count; i++) {
            Ivar ivar = ivarList[i];
            
            NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
            //将第一个字符截取掉,获得属性名
            NSString *propertyName = [name substringFromIndex:1];
    
            //前面为成员变量,后面为属性名
            NSLog(@"%@:%@",name,propertyName);
            
        }
    

    查看控制台打印结果(可以通过command+F搜索):

    控制台结果,部分未截图
    1.2 解决问题
     UITextField *textFiled = [[UITextField alloc]initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 40)];
        textFiled.backgroundColor = [UIColor clearColor];
        textFiled.layer.borderColor = [UIColor whiteColor].CGColor;
        textFiled.layer.borderWidth = 1;
        textFiled.layer.cornerRadius = 4;
        textFiled.placeholder = @"我是重生的占位符";
        
        [textFiled setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
        [textFiled setValue:[UIFont systemFontOfSize:11] forKeyPath:@"_placeholderLabel.font"];
        
        [self.view addSubview:textFiled];
    
    1.3 效果展示
    模拟器展示效果

    但是该属性变量属于苹果的私有API,使用该方法上线有可能会被拒,慎用.

    2 项目中navigationBar的backItem不显示文字

    需求:项目中的大部分navigationBar的backItem不需要文字,只需要返回箭头.

    2.1 在不需要backItem文字的视图控制器被push之前,设置backItem
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]init];
        backItem.title = @"";
        self.navigationItem.backBarButtonItem = backItem;
    

    设置该方法需要注意两点:需要在Push之前这是backBarButtonItem,否则无效;必须初始化一个新的UIBarButtonItem对象,设置其title为空并赋值,直接设置backBarButtonItem.title无效
    页面多的话,可以设置BaseController在其中设置,新生成的Controller继承即可.

    2.2 使用runtime解决

    但是总觉的方法一这个不是解决问题的完美方法,想找到一个完美实现该需求且一劳永逸的方法。
    使用category为UINavigationController增加扩展方法

    //在程序启动时,使用runtime交换系统与自定义的方法
    +(void)load{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Method originalMethod = class_getInstanceMethod(self, @selector(backBarButtonItem));
            
            Method customMethod = class_getInstanceMethod(self, @selector(CM_BackBarButtonItem));
            method_exchangeImplementations(originalMethod, customMethod);
        });
    }
    
    static char CMCustomBackBarButtonKey;
    
    -(UIBarButtonItem *)CM_BackBarButtonItem{
        UIBarButtonItem *item = [self CM_BackBarButtonItem];
        if (item) {
            return item;
        }
        item = objc_getAssociatedObject(self, &CMCustomBackBarButtonKey);
        if (!item) {
            item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:NULL];
            objc_setAssociatedObject(self, &CMCustomBackBarButtonKey, item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        return item;
    }
    
    2.3 效果展示
    展示效果

    3 字体适配

    项目中字体适配是很常见的情况,主要适配6p机型,常见的适配方法是在设置字体大小的时候乘以一个宏定义比例,该方法需要在每次设置字体的时候都要乘以比例,比较繁琐.
    runtime可以通过自定义的方法替换系统方法,因此又想到了runtime

    3.1 解决思路:

    需要设置字体大小的控件为UILabel和UIButton,通过分类分别为两个类扩展方法,自定义方法在子视图加载之前重新设置控件的字体大小(通过判断是否为6p乘以一个自定义的比例)

    3.2 解决方法:
    @implementation UIButton (Common)
    + (void)load {
        //方法交换应该被保证,在程序中只会执行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            SEL systemSel = @selector(willMoveToSuperview:);
            SEL swizzSel = @selector(CM_WillMoveToSuperview:);
            Method systemMethod = class_getInstanceMethod([self class], systemSel);
            Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
            
            //首先动态添加方法,实现是被交换的方法,返回值表示添加成功还是失败
            BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
            if (isAdd) {
                //如果成功,说明类中不存在这个方法的实现
                //将被交换方法的实现替换到这个并不存在的实现
                class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
            } else {
                //否则,交换两个方法的实现
                method_exchangeImplementations(systemMethod, swizzMethod);
            }
            
        });
    }
    
    - (void)CM_WillMoveToSuperview:(UIView *)newSuperview {
        
        [self CM_WillMoveToSuperview:newSuperview];
        //    if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
        //        return;
        //    }
        if (self) {
    //不需要适配的,通过设置tag值跳过
            if (self.tag != 10086) {
                self.titleLabel.font = [UIFont systemFontOfSize:self.titleLabel.font.pointSize*SizeScale];
            } else {
                       }
        }
    }
    
    @end
    

    UILable同样可以使用替换系统的方法实现字体的适配.

    效果就不展示,具体大家可以自己运行在模拟器查看。

    3.3 设计优化

    将UILabel的分类和UIButton的分类合并写在一个类里面。

    .h文件

    .m文件

    /**
     button的字体适配
     */
    @implementation UIButton (Common)
    + (void)load {
        //方法交换应该被保证,在程序中只会执行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            SEL systemSel = @selector(willMoveToSuperview:);
            SEL swizzSel = @selector(CM_WillMoveToSuperview:);
            Method systemMethod = class_getInstanceMethod([self class], systemSel);
            Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
            
            //首先动态添加方法,实现是被交换的方法,返回值表示添加成功还是失败
            BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
            if (isAdd) {
                //如果成功,说明类中不存在这个方法的实现
                //将被交换方法的实现替换到这个并不存在的实现
                class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
            } else {
                //否则,交换两个方法的实现
                method_exchangeImplementations(systemMethod, swizzMethod);
            }
            
        });
    }
    
    - (void)CM_WillMoveToSuperview:(UIView *)newSuperview {
        
        [self CM_WillMoveToSuperview:newSuperview];
        //    if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
        //        return;
        //    }
        if (self) {
            if (self.tag != 10086) {
                self.titleLabel.font = [UIFont systemFontOfSize:self.titleLabel.font.pointSize*SizeScale];
            } else {
                       }
        }
    }
    
    @end
    
    #pragma mark --- 字体设置
    @implementation UILabel (Common)
    
    + (void)load {
        
        //方法交换应该被保证,在程序中只会执行一次
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            SEL systemSel = @selector(willMoveToSuperview:);
            SEL swizzSel = @selector(CM_WillMoveToSuperview:);
            Method systemMethod = class_getInstanceMethod([self class], systemSel);
            Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
            
            //首先动态添加方法,实现是被交换的方法,返回值表示添加成功还是失败
            BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
            if (isAdd) {
                //如果成功,说明类中不存在这个方法的实现
                //将被交换方法的实现替换到这个并不存在的实现
                class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
            } else {
                //否则,交换两个方法的实现
                method_exchangeImplementations(systemMethod, swizzMethod);
            }
            
        });
    }
    
    - (void)CM_WillMoveToSuperview:(UIView *)newSuperview {
        
        [self CM_WillMoveToSuperview:newSuperview];
        //    if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
        //        return;
        //    }
        if (self) {
            if (self.tag != 10086) {
                self.font = [UIFont systemFontOfSize:self.font.pointSize*SizeScale];
            } else {
            }
        }
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:Runtime(二) -- 项目实战篇

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