欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS改變UITextField占位文字顏色的三種方法

 更新時(shí)間:2017年01月24日 10:49:03   作者:Mazy_ma  
這篇文章主要為大家詳細(xì)介紹了iOS改變UITextField的占位文字顏色的三種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

有時(shí),UITextField自帶的占位文字的顏色太淺或者不滿足需求,所以需要修改,而UITextField沒有直接的屬性去修改占位文字的顏色,所以只能通過其他間接方式去修改。

例如:系統(tǒng)默認(rèn)的占位文字顏色太淺

這里寫圖片描述

需要加深顏色,或者改變顏色
示例:

這里寫圖片描述

核心代碼

方法一:通過attributedPlaceholder屬性修改占位文字顏色


 CGFloat viewWidth = self.view.bounds.size.width;
 CGFloat textFieldX = 50;
 CGFloat textFieldH = 30;
 CGFloat padding = 30;

 UITextField *textField = [[UITextField alloc] init];
 textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH);
 textField.borderStyle = UITextBorderStyleRoundedRect; // 邊框類型
 textField.font = [UIFont systemFontOfSize:14];
 NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"請輸入占位文字" attributes:
 @{NSForegroundColorAttributeName:[UIColor redColor],
     NSFontAttributeName:textField.font
   }];
 textField.attributedPlaceholder = attrString;
 [self.view addSubview:textField];

方法二:通過KVC修改占位文字顏色

 UITextField *textField1 = [[UITextField alloc] init];
 textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);
 textField1.borderStyle = UITextBorderStyleRoundedRect;
 textField1.placeholder = @"請輸入占位文字";
 textField1.font = [UIFont systemFontOfSize:14];
 // "通過KVC修改占位文字的顏色"
 [textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
 [self.view addSubview:textField1];

方法三:通過重寫UITextField的drawPlaceholderInRect:方法修改占位文字顏色

1、自定義一個(gè)TextField繼承自UITextField
2、重寫drawPlaceholderInRect:方法
3、在drawPlaceholderInRect方法中設(shè)置placeholder的屬性

// 重寫此方法
-(void)drawPlaceholderInRect:(CGRect)rect {
 // 計(jì)算占位文字的 Size
 CGSize placeholderSize = [self.placeholder sizeWithAttributes:
        @{NSFontAttributeName : self.font}];

 [self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:
 @{NSForegroundColorAttributeName : [UIColor blueColor],
     NSFontAttributeName : self.font}];
}

總結(jié):

1、當(dāng)我們使用純代碼創(chuàng)建UITextField時(shí),用第二種方法(KVC)修改占位文字顏色是最便捷的
2、當(dāng)我們使用XIB或者Storyboard創(chuàng)建UITextField時(shí),通過自定義UITextField,修改占位文字顏色是最適合的。
3、我們也可以在第三種重寫方法中,通過結(jié)合第二種方法中的KVC修改屬性來實(shí)現(xiàn)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論