一、 UITextField的基本使用
- 設(shè)置光標(biāo)顏色
// 設(shè)置光標(biāo)顏色
self.tintColor=[UIColor whiteColor];
- 設(shè)置輸入文字顏色
// 設(shè)置輸入文字顏色
self.textColor=[UIColor whiteColor];
- 通過代理設(shè)置開始輸入和結(jié)束輸入時占位文字的顏色
一般情況下最好不要UITextView自己成為代理或者監(jiān)聽者
// 開始編輯
[self addTarget:self action:@selector(textDidBeginEdit)forControlEvents:UIControlEventEditingDidBegin];
// 結(jié)束編輯
[self addTarget:self action:@selector(textDidEndEdit)forControlEvents:UIControlEventEditingDidEnd];
二、UITextField占位文字顏色修改
1、通過設(shè)置attributedPlaceholder屬性修改
- (void)setPlaceholderColor:(UIColor*)color {
NSMutableDictionary *attrDict = [NSMutableDictionary dictionary];
attrDict[NSForegroundColorAttributeName] = color;
NSAttributedString *attr= [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrDict];
self.attributedPlaceholder = attr;
}
2、通過KVC拿到UITextView的占位label就可修改顏色
- (void)setPlaceholderLabelColor:(UIColor *)color {
UILabel*placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
placeholderLabel.textColo r= color;
}
3、通過Runtime來設(shè)置UITextView占位文字顏色
給UITextField添加一個占位文字顏色屬性,而給系統(tǒng)類添加屬性,就必須使用runtime來實(shí)現(xiàn), 分類只能生成屬性名
自定義setPlaceholder:并與系統(tǒng)setPlaceholder:方法交換
- 交換系統(tǒng)setPlaceholder:設(shè)置占位文字和自定義my_setPlaceholder:方法
- 交換原因:如果外界使用先設(shè)置了占位顏色,再設(shè)置占位文字,設(shè)置顏色時沒有文字設(shè)置不成功
- 交換設(shè)置占位文字方法,外界調(diào)用系統(tǒng)方法設(shè)置占位文字時,會自動調(diào)用自定義的設(shè)置占位文字方法,再調(diào)用系統(tǒng)設(shè)置占位文字方法,在自定義設(shè)置占位文字方法中自動設(shè)置占位文字顏色
具體實(shí)現(xiàn)
1> 給UITextView添加一個分類, 聲明一個placeholderColor屬性
// .h文件
#import <UIKit/UIKit.h>
@interface UITextField (Placeholder)
@property UIColor *placeholderColor;
@end
2>.實(shí)現(xiàn)placeholderColor屬性的setter和getter方法
// .m文件
#import "UITextField+Placeholder.h"
#import <objc/message.h>
NSString * const placeholderColorName = @"placeholderColor";
@implementation UITextField (Placeholder)
+ (void)load {
// 獲取setPlaceholder
Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
// 獲取ld_setPlaceholder
Method ld_setPlaceholder = class_getInstanceMethod(self, @selector(ld_setPlaceholder:));
// 交換方法
method_exchangeImplementations(setPlaceholder, ld_setPlaceholder);
}
// OC最喜歡懶加載,用的的時候才會去加載
// 需要給系統(tǒng)UITextField添加屬性,只能使用runtime
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
// 設(shè)置關(guān)聯(lián)
objc_setAssociatedObject(self,(__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 設(shè)置占位文字顏色
UILabel *placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor {
// 返回關(guān)聯(lián)
return objc_getAssociatedObject(self, (__bridge const void *)(placeholderColorName));
}
// 設(shè)置占位文字,并且設(shè)置占位文字顏色
- (void)ld_setPlaceholder:(NSString *)placeholder {
// 1.設(shè)置占位文字
[self ld_setPlaceholder:placeholder];
// 2.設(shè)置占位文字顏色
self.placeholderColor = self.placeholderColor;
}
@end