iOS中修改UITextField占位符字體顏色的方法總結
前言
最近學了UITextField控件, 感覺在里面設置占位符非常好, 給用戶提示信息, 于是就在想占位符的字體和顏色能不能改變呢?下面是小編的一些簡單的實現(xiàn),有需要的朋友們可以參考。
修改UITextField的占位符文字顏色主要有三個方法:
1、使用attributedPlaceholder屬性
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil
2、重寫drawPlaceholderInRect方法
- (void)drawPlaceholderInRect:(CGRect)rect;
3、修改UITextField內(nèi)部placeholderLaber的顏色
[textField setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];
以下是詳細的實現(xiàn)過程
給定場景,如在注冊登錄中,要修改手機號和密碼TextField的placeholder
的文字顏色。
效果對比
使用前
使用后
使用attributedPlaceholder
自定義GYLLoginRegisterTextField
類,繼承自UITextField;實現(xiàn)awakeFromNib()
方法,如果使用storyboard
,那么修改對應的UITextField的CustomClass
為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
重寫drawPlaceholderInRect方法
與方法一同樣,自定義GYLLoginRegisterTextField
,繼承自UITextField,重寫drawPlaceholderInRect
方法,后續(xù)相同
代碼如下:
#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
修改UITextField內(nèi)部placeholderLaber的顏色
使用KVC機制,找到UITextField內(nèi)部的修改站位文字顏色的屬性:placeholderLaber.textColor
代碼如下:
#import "GYLLoginRegisterTextField.h" @implementation GYLLoginRegisterTextField - (void)awakeFromNib { self.tintColor = [UIColor whiteColor]; //設置光標顏色 //修改占位符文字顏色 [self setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"]; } @end
第三種方法比較簡單,建議可以將此封裝:擴展UITextField,新建category,添加placeholderColor
屬性,使用KVC重寫set
和get
方法。
總結
以上就是這篇文章的全部內(nèi)容了,希望能對大家開發(fā)iOS有所幫助,如果有疑問大家可以留言交流。
相關文章
詳解Obejective-C中將JSON數(shù)據(jù)轉(zhuǎn)為模型的方法
這篇文章主要介紹了Obejective-C中JSON數(shù)據(jù)轉(zhuǎn)為模型的方法,同時介紹了使用jastor庫的方法,需要的朋友可以參考下2016-03-03