// // MSRTL.m // YuMi // // Created by duoban on 2024/4/11. // #import "UILabel+MSRTL.h" #import "NSMutableAttributedString+MSRTL.h" BOOL isMSRTLString(NSString *string) { if ([string hasPrefix:@"\u202B"] || [string hasPrefix:@"\u202A"]) { return YES; } return NO; } NSString * MSRTLString(NSString *string) { if (string.length == 0 || isMSRTLString(string)) { return string; } if (isMSRTL()) { string = [@"\u202B" stringByAppendingString:string]; } else { string = [@"\u202A" stringByAppendingString:string]; } return string; } @implementation UILabel (MSRTL) + (void)load { Method oldInitMethod = class_getInstanceMethod(self,@selector(initWithFrame:)); Method newInitMethod = class_getInstanceMethod(self, @selector(msrtl_initWithFrame:)); method_exchangeImplementations(oldInitMethod, newInitMethod); //交换成功 Method oldTextAlignmentMethod = class_getInstanceMethod(self,@selector(setTextAlignment:)); Method newTextAlignmentMethod = class_getInstanceMethod(self, @selector(msrtl_setTextAlignment:)); method_exchangeImplementations(oldTextAlignmentMethod, newTextAlignmentMethod); //交换成功 Method oldTextMethod1 = class_getInstanceMethod(self,@selector(setAttributedText:)); Method newTextMethod1 = class_getInstanceMethod(self, @selector(msrtl_setAttributedText:)); method_exchangeImplementations(oldTextMethod1, newTextMethod1); } -(void)msrtl_setAttributedText:(NSAttributedString *)attributedText{ if(attributedText == nil)return; NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc]init]; if([NSStringFromClass([self class])isEqualToString:@"UITextFieldLabel"] || self.textAlignment == NSTextAlignmentCenter){ if (isMSRTL() ) { // 插入RTL [attributedString appendAttributedString:[NSMutableAttributedString createBlankAttributeToMSRTL]]; } [attributedString appendAttributedString:attributedText]; [self msrtl_setAttributedText:attributedString]; return; } if (isMSRTL() ) { // 插入RTL [attributedString appendAttributedString:[NSMutableAttributedString createBlankAttributeToMSRTL]]; } [attributedString appendAttributedString:attributedText]; [self msrtl_setAttributedText:attributedString]; } - (instancetype)msrtl_initWithFrame:(CGRect)frame { if ([self msrtl_initWithFrame:frame]) { self.textAlignment = NSTextAlignmentNatural; } return self; } - (void)msrtl_setTextAlignment:(NSTextAlignment)textAlignment { if (isMSRTL()) { if (textAlignment == NSTextAlignmentNatural || textAlignment == NSTextAlignmentLeft) { textAlignment = NSTextAlignmentRight; } else if (textAlignment == NSTextAlignmentRight) { textAlignment = NSTextAlignmentLeft; } } [self msrtl_setTextAlignment:textAlignment]; } @end