一丶原理
修改placeholder的方法:
1.
myTextField.placeholder = @"請(qǐng)輸入用戶名!";
[myTextField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[myTextField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
2.建議使用:
NSMutableAttributedString *placeholderAtbString = [[NSMutableAttributedString alloc] initWithString:placeholder];
[placeholderAtbString addAttribute:NSForegroundColorAttributeName
value:kMianColor_8997B0
range:NSMakeRange(0, placeholder.length)];
self.attributedPlaceholder = placeholderAtbString;
修改全局:
runtime替換系統(tǒng)placeholder方法;
二丶代碼
#import "UITextField+HYBPlaceHolder.h"
@implementation UITextField (HYBPlaceHolder)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class selfClass = [self class];
SEL oriSEL = @selector(setPlaceholder:);
Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);
SEL cusSEL = @selector(ZB_setPlaceholder:);
Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);
BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
if (addSucc) {
class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else {
method_exchangeImplementations(oriMethod, cusMethod);
}
});
}
- (void)ZB_setPlaceholder:(NSString *)placeholder{
NSMutableAttributedString *placeholderAtbString = [[NSMutableAttributedString alloc] initWithString:placeholder];
[placeholderAtbString addAttribute:NSForegroundColorAttributeName
value:kMianColor_8997B0
range:NSMakeRange(0, placeholder.length)];
self.attributedPlaceholder = placeholderAtbString;
[self ZB_setPlaceholder:placeholder];
}
@end
注意事項(xiàng):
項(xiàng)目中的Placeholder必須用代碼去設(shè)置,xib的并不走setPlaceholder方法;
xib實(shí)現(xiàn)代碼:
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class selfClass = [self class];
{
SEL oriSEL = @selector(initWithCoder:);
Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);
SEL cusSEL = @selector(ZB_initWithCoder:);
Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);
BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
if (addSucc) {
class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else {
method_exchangeImplementations(oriMethod, cusMethod);
}
}
});
}
- (instancetype)ZB_initWithCoder:(NSCoder *)coder
{
id obj = [self ZB_initWithCoder:coder];
if (obj) {
[self setValue:kColor_8997B0 forKeyPath:@"_placeholderLabel.textColor"];
}
return obj;
}