iOS 重写UILabel的text属性

由于项目中临时变更对所有的UILabel的文字要做表情兼容,所以采用次方是,请看代码:

 

//重写initialize

+ (void)initialize

{

    // 获取到UILabel中setText对应的method

    Method setText =class_getInstanceMethod([UILabel class], @selector(setText:));

    Method setTextMySelf =class_getInstanceMethod([self class],@selector(setTextHooked:));

    

    // 将目标函数的原实现绑定到setTextOriginalImplemention方法上

    IMP setTextImp =method_getImplementation(setText);

    class_addMethod([UILabel class], @selector(setTextOriginal:), setTextImp,method_getTypeEncoding(setText));

    

    //然后用我们自己的函数的实现,替换目标函数对应的实现

    IMP setTextMySelfImp =method_getImplementation(setTextMySelf);

    class_replaceMethod([UILabel class], @selector(setText:), setTextMySelfImp,method_getTypeEncoding(setText));

    

}

 

 

- (void)setTextHooked:(NSString *)string

{

    

    //    //在这里插入过滤算法

    //    string = [stringstringByReplacingOccurrencesOfString:@"

    //              " withString:@"\r\n"];

    

    // do something what ever youwant

  

    string = App_EmojiCheatUniCode(string);

    

    // invoke originalimplemention

    [self performSelector:@selector(setTextOriginal:) withObject:string];

    

}

 

#define App_EmojiCheatUniCode(str)  [App_ShowString(str) jk_stringByReplacingEmojiCheatCodesWithUnicode]

#define App_ShowString(str) (App_IsEmpty(str)?@"":str)

 

jk_stringByReplacingEmojiCheatCodesWithUnicode方法请查看  JXCategoryView ,在gitHub搜索即可查到。

 

你可能感兴趣的:(iOS)