寫在前面: 在日常編程中經常有需要修改UITextField的placeholder的顯示樣式,每次做法都可能不太一樣,實現的復雜程度也可能存在很大的差別,為了能在這個需求上不再浪費時間和精力去完成,下面總結了集中自認為比較簡便的方式去實現,大致有四種方式如下:
-
方式一
- 通過富文本NSAttributedString進行設置
// 屬性字典 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; // 創建富文本字符串對象 NSAttributedString *placeholder = [[NSAttributedString alloc] initWithString:@"請輸入手機號" attributes:attrs]; // 為textfield對象設置占位文字 self.phoneField.attributedPlaceholder = placeholder;
-
方式二
- 通過NSMutableAttributedString進行設置
- NSMutableAttributedString相對于NSAttributedString的有點在于可以設置任意位置的文字屬性,原因是多了一個下面的方法:
// 這個方法能設置不同位置的文字屬性 -(void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
- 下面展示設置textField的占位文字顏色
NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:@"請輸入手機號"]; [placeholder setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:10] } range:NSMakeRange(0, 1)]; [placeholder setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor] } range:NSMakeRange(1, 2)]; self.phoneField.attributedPlaceholder = placeholder;
-
方式三
- 寫一個LJTextField繼承自UITextField,并重寫下面的方法就可以了:
// 重寫這個方法,在方法內部重新畫placeholder的樣式 -(void)drawPlaceholderInRect:(CGRect)rect;
- 例如:
#import "LJTextField.h" @implementation LJTextField - (void)drawPlaceholderInRect:(CGRect)rect { // 拿到自己的placeholder設置傳入設置的范圍和文字的屬性字典就可以了 [self.placeholder drawInRect:self.frame withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10]}]; } @end
-
方式四
利用運行時獲取UITextField隱藏的屬性,再用KVC為其賦值
-
利用運行時技術:先簡單的科普一下運行時吧!
- 運行時(又稱Runtime)
- 是蘋果官方一套C語言庫
- 能做很多底層的操作,如:訪問隱藏的一些成員變量/成員方法;
-
獲取UITextField的隱藏屬性
- 導入頭文件
#import <objc/runtime.h>
- 寫入下面的代碼
// 在這個方法里面利用運行時找到想要隱藏式屬性并打印
+(void)initialize{
unsigned int count = 0;
// 拷貝出所有的成員變量列表
Ivar *ivars = class_copyIvarList([UITextField class], &count);for (int i = 0; i<count; i++) {
// 取出成員變量
// Ivar ivar = *(ivars + i);
Ivar ivar = ivars[i];// 打印成員變量名字 XMGLog(@"%s %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
}
// 釋放
free(ivars);
}
```- 在初始化方法中利用KVC為隱藏的成員變量賦值就可以了
- (void)awakeFromNib { // 分開寫 修改占位文字顏色 //UILabel *placeholderLabel = [self valueForKeyPath:@"_placeholderLabel"]; placeholderLabel.textColor = [UIColor redColor]; //合并寫 [self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; // 設置光標顏色和文字顏色一致 self.tintColor = self.textColor; }
- 導入頭文件
總結:
- 上面的四種思路均可以改變UITextField的占位文字顏色,提供了不同的選擇,但是placeholder的文字顏色的設置方式,絕對不止上面的集中方式,如果有更多的,簡便的方式,還希望大家能夠互相交流.