// // UITextField+MSRTL.m // YuMi // // Created by duoban on 2024/4/11. // #import "UITextField+MSRTL.h" @implementation UITextField (MSRTL) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Method oldInitMethod = class_getInstanceMethod(self,@selector(initWithFrame:)); Method newInitMethod = class_getInstanceMethod(self, @selector(msrtl_initWithFrame:)); method_exchangeImplementations(oldInitMethod, newInitMethod); //交换成功 // Method oldTextMethod1 = class_getInstanceMethod(self,@selector(setPlaceholder:)); // Method newTextMethod1 = class_getInstanceMethod(self, @selector(msrtl_setPlaceholder:)); // method_exchangeImplementations(oldTextMethod1, newTextMethod1); //交换成功 // // Method oldTextMethod = class_getInstanceMethod(self,@selector(setTextAlignment:)); // Method newTextMethod = class_getInstanceMethod(self, @selector(msrtl_setTextAlignment:)); // method_exchangeImplementations(oldTextMethod, newTextMethod); //交换成功 Method oldMethod = class_getInstanceMethod(self,@selector(setAttributedPlaceholder:)); Method newMethod = class_getInstanceMethod(self, @selector(msrtl_setAttributedPlaceholder:)); method_exchangeImplementations(oldMethod, newMethod); //交换成功 }); } - (void)msrtl_setTextAlignment:(NSTextAlignment)textAlignment { if (isMSRTL()) { if (textAlignment == NSTextAlignmentNatural || textAlignment == NSTextAlignmentLeft) { textAlignment = NSTextAlignmentRight; } else if (textAlignment == NSTextAlignmentRight) { textAlignment = NSTextAlignmentLeft; } } [self msrtl_setTextAlignment:textAlignment]; } - (instancetype)msrtl_initWithFrame:(CGRect)frame { if ([self msrtl_initWithFrame:frame]) { if(isMSRTL()){ self.textAlignment = NSTextAlignmentRight; } } return self; } - (void)msrtl_setAttributedPlaceholder:(NSAttributedString *)attributedPlaceholder{ NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithAttributedString:attributedPlaceholder]; NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init]; NSTextAlignment textAli = NSTextAlignmentLeft; paragraph.alignment = textAli; [att addAttributes:@{NSParagraphStyleAttributeName: paragraph} range:[attributedPlaceholder.string rangeOfString:attributedPlaceholder.string]]; [self msrtl_setAttributedPlaceholder:att]; } - (void)msrtl_setPlaceholder:(NSString *)placeholder { if(placeholder == nil)return; NSAttributedString * attribute = [[NSAttributedString alloc] initWithString:placeholder]; self.attributedPlaceholder = attribute; } @end