美文网首页
iOS:便捷颜色转换工具类

iOS:便捷颜色转换工具类

作者: 豆浆油条cc | 来源:发表于2019-11-23 16:35 被阅读0次

    因为项目中用颜色转换一般根据高保真的16进制进行转换,所以使用runtime特性封装了一个工具类。
    原理:通过获取类的所有属性,根据属性名称对属性使用KVC赋值。
    缺点:每次新增加的颜色都需要添加属性,并且因为是Load方法执行函数,需要重新启动
    项目。

    Github:https://github.com/qw9685/colorTool

    .m实现:

    
    //
    //  ccColor.h
    //
    //  Created by 崔畅 on 2019/9/4.
    //  Copyright © 2019年 mac. All rights reserved.
    //
    
    
    #import "ccColor.h"
    #import <objc/runtime.h>
    
    #define UIColorFromHex(s) [UIColor colorWithRed:(((s & 0xFF0000) >> 16))/255.0 green:(((s & 0xFF00) >> 8))/255.0 blue:((s & 0xFF))/255.0 alpha:1.0]
    
    @implementation ccColor
    
    +(void)load{
        //创建对象 + 属性赋值
        [myColor displayCurrentModleProperty];
    }
    
    + (instancetype)shareInstance{
        
        static ccColor *share = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            share = [[super allocWithZone:NULL] init];
        });
        return share;
    }
    
    //返回当前类的所有属性
    + (NSArray*)getProperties{
        
        unsigned int count;
        objc_property_t *properties = class_copyPropertyList([self class], &count);
        // 遍历
        NSMutableArray *mArray = [NSMutableArray array];
        for (int i = 0; i < count; i++) {
            objc_property_t property = properties[i];
            
            const char *propertyCharType = property_getAttributes(property);
            NSString *propertyType = [NSString stringWithUTF8String:propertyCharType];
            
            //过滤非UIColor类型
            if ([propertyType containsString:@"UIColor"]) {
                const char *propertyCharName = property_getName(property);
                NSString *propertyName = [NSString stringWithCString:propertyCharName encoding:NSUTF8StringEncoding];
                [mArray addObject:propertyName];
            }
        }
        
        free(properties);
        return mArray.copy;
    }
    
    - (void) displayCurrentModleProperty{
    
        //赋值
        NSArray *array = [ccColor getProperties];
        for (int i = 0; i < array.count; i ++) {
            NSString* propertyName = array[i];
            [myColor setValue:UIColorFromHex([propertyName integerValue]) forKey:propertyName];
        }
    }
    
    @end
    

    申明:


    屏幕快照 2019-11-23 下午4.28.45.png

    使用:


    屏幕快照 2019-11-23 下午4.28.14.png

    相关文章

      网友评论

          本文标题:iOS:便捷颜色转换工具类

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