用過 UITextField 的人都喜歡拿占位符(placeholder)給使用者提示,但系統預設的灰色往往和設計稿搭不上。本文整理三種修改占位符顏色的做法,並附上實作細節。
1. 使用 attributedPlaceholder 屬性
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil
2. 覆寫 drawPlaceholderInRect 方法
- (void)drawPlaceholderInRect:(CGRect)rect;
3. 用 KVC 改動內部的 placeholderLabel
[textField setValue:[UIColor grayColor] forKeyPath:@"placeholderLaber.textColor"];
以登入註冊頁為例,要改掉手機號與密碼兩個輸入框的占位文字顏色。
效果對比

使用前

使用後
自訂一個 GYLLoginRegisterTextField 類別並繼承 UITextField,在 awakeFromNib 中設定。若使用 storyboard,只要把對應輸入框的 Custom Class 改成 GYLLoginRegisterTextField 即可。
#import "GYLLoginRegisterTextField.h" @implementation GYLLoginRegisterTextField - (void)awakeFromNib { self.tintColor = [UIColor whiteColor]; //設置光標顏色 //修改占位符文字顏色 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs]; } @end
這個做法最正規,除了顏色,字型等其他屬性也能一併透過 attributes 設定。
一樣繼承 UITextField,改由自己畫出占位文字,因此連位置都能微調。
#import "GYLLoginRegisterTextField.h" @implementation GYLLoginRegisterTextField - (void)awakeFromNib { self.tintColor = [UIColor whiteColor]; //設置光標顏色 } - (void)drawPlaceholderInRect:(CGRect)rect { NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; attrs[NSFontAttributeName] = self.font; //畫出占位符 CGRect placeholderRect; placeholderRect.size.width = rect.size.width; placeholderRect.size.height = rect.size.height; placeholderRect.origin.x = 0; placeholderRect.origin.y = (rect.size.height - self.font.lineHeight) * 0.5; [self.placeholder drawInRect:placeholderRect withAttributes:attrs]; //或者 /* CGPoint placeholderPoint = CGPointMake(0, (rect.size.height - self.font.lineHeight) * 0.5); [self.placeholder drawAtPoint:placeholderPoint withAttributes:attrs]; */ } @end
利用 KVC 直接摸到 UITextField 內部的 placeholderLabel.textColor:
#import "GYLLoginRegisterTextField.h" @implementation GYLLoginRegisterTextField - (void)awakeFromNib { self.tintColor = [UIColor whiteColor]; //設置光標顏色 //修改占位符文字顏色 [self setValue:[UIColor grayColor] forKeyPath:@"placeholderLaber.textColor"]; } @end
第三種寫法最省事,可以進一步封裝:擴充 UITextField 建立 category,加上一個 placeholderColor 屬性,並覆寫它的 setter 與 getter。不過要留意,這種方式依賴私有外觀,系統改版時有失效風險,正式專案建議優先採用前兩種。
三種方式各有取捨:追求穩定與可移植性選 attributedPlaceholder;需要完全掌控排版就覆寫 drawPlaceholderInRect;只是想快速改個顏色,KVC 最方便。以上就是本文的全部內容,若有疑問歡迎留言交流。