一、 UITextField的基本使用
- 設置光標顏色
// 設置光標顏色
self.tintColor=[UIColor whiteColor];
- 設置輸入文字顏色
// 設置輸入文字顏色
self.textColor=[UIColor whiteColor];
- 通過代理設置開始輸入和結束輸入時占位文字的顏色
一般情況下最好不要UITextView自己成為代理或者監聽者
// 開始編輯
[self addTarget:self action:@selector(textDidBeginEdit)forControlEvents:UIControlEventEditingDidBegin];
// 結束編輯
[self addTarget:self action:@selector(textDidEndEdit)forControlEvents:UIControlEventEditingDidEnd];
二、UITextField占位文字顏色修改
1、通過設置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來設置UITextView占位文字顏色
給UITextField添加一個占位文字顏色屬性,而給系統類添加屬性,就必須使用runtime來實現, 分類只能生成屬性名
自定義setPlaceholder:并與系統setPlaceholder:方法交換
- 交換系統setPlaceholder:設置占位文字和自定義my_setPlaceholder:方法
- 交換原因:如果外界使用先設置了占位顏色,再設置占位文字,設置顏色時沒有文字設置不成功
- 交換設置占位文字方法,外界調用系統方法設置占位文字時,會自動調用自定義的設置占位文字方法,再調用系統設置占位文字方法,在自定義設置占位文字方法中自動設置占位文字顏色
具體實現
1> 給UITextView添加一個分類, 聲明一個placeholderColor屬性
// .h文件
#import <UIKit/UIKit.h>
@interface UITextField (Placeholder)
@property UIColor *placeholderColor;
@end
2>.實現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最喜歡懶加載,用的的時候才會去加載
// 需要給系統UITextField添加屬性,只能使用runtime
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
// 設置關聯
objc_setAssociatedObject(self,(__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 設置占位文字顏色
UILabel *placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor {
// 返回關聯
return objc_getAssociatedObject(self, (__bridge const void *)(placeholderColorName));
}
// 設置占位文字,并且設置占位文字顏色
- (void)ld_setPlaceholder:(NSString *)placeholder {
// 1.設置占位文字
[self ld_setPlaceholder:placeholder];
// 2.設置占位文字顏色
self.placeholderColor = self.placeholderColor;
}
@end