UITextField是IOS開發(fā)中用戶交互中重要的一個控件,常被用來做賬號密碼框,輸入信息框等。
觀察效果圖
UITextField有以下幾種特點:
1.默認占位文字是灰色的
2.當光標點上去時,占位文字變?yōu)榘咨?br />
3.光標是白色的
接下來我們通過不同的方法來解決問題
一.將xib中的UITextField與代碼關聯(lián)
通過NSAttributeString方法來更改占位文字的屬性(void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view from its nib.//文字屬性NSMutableDictionary *dict = [NSMutableDictionary dictionary];dict[NSForegroundColorAttributeName] = [UIColor grayColor];//帶有屬性的文字(富文本屬性)NSAttributeStringNSAttributedString *attr = [[NSAttributedString alloc] initWithString:@"手機號" attributes:dict];self.phoneField.attributedPlaceholder = attr;}
但是這種方法只能做出第一種效果,而且不具有通用性。
二.自定義一個UITextField的類
重寫它的drawPlaceholderInRect方法
//畫出占位文字- (void)drawPlaceholderInRect:(CGRect)rect {[self.placeholder drawInRect:CGRectMake(0, 13, self.size.width, 25) withAttributes:@{NSForegroundColorAttributeName : [UIColor grayColor],NSFontAttributeName : [UIFont systemFontOfSize:14]}];}
這個方法和上一個方法類似,只能做出第一種效果,但這個具有通用性
三.利用Runtime運行時機制
Runtime是官方的一套C語言庫
能做出很多底層的操作(比如訪問隱藏的一些成員變量/成員方法)
(void)initialize {unsigned int count = 0;Ivar *ivars = class_copyIvarList([UITextField class] , &count);for (int i = 0; i < count; i++) {//取出成員變量Ivar ivar = *(ivars + i);//打印成員變量名字DDZLog(@"%s",ivar_getName(ivar));}}
利用class_copyIvarList這個C函數(shù),將所有的成員變量打印出來
這樣我們就可以直接通過KVC進行屬性設置了
- (void)awakeFromNib {//修改占位文字顏色[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; //設置光標顏色和文字顏色一致self.tintColor = self.textColor;}
通過這個方法可以完成所有的效果,既具有通用性也簡單
最后一個效果是
在獲得焦點時改變占位文字顏色
在失去焦點時再改回去
//獲得焦點時- (BOOL)becomeFirstResponder {//改變占位文字顏色[self setValue:self.textColor forKeyPath:@"_placeholderLabel.textColor"]; return [super becomeFirstResponder];}//失去焦點時- (BOOL)resignFirstResponder {//改變占位文字顏色[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; return [super resignFirstResponder];}
新聞熱點
疑難解答