有時,UITextField自帶的占位文字的顏色太淺或許不滿足需求,所以需求修正,而UITextField沒有直接的屬性去修正占位文字的顏色,所以只能經過其他直接方式去修正。
例如:零碎默許的占位文字顏色太淺

需求加深顏色,或許改動顏色
示例:

中心代碼
辦法一:經過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、自定義一個TextField承繼自UITextField
2、重寫drawPlaceholderInRect:辦法
3、在drawPlaceholderInRect辦法中設置placeholder的屬性
// 重寫此辦法
-(void)drawPlaceholderInRect:(CGRect)rect {
// 計算占位文字的 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}];
}
總結:
1、當我們運用純代碼創立UITextField時,用第二種辦法(KVC)修正占位文字顏色是最便捷的
2、當我們運用XIB或許Storyboard創立UITextField時,經過自定義UITextField,修正占位文字顏色是最合適的。
3、我們也可以在第三種重寫辦法中,經過結合第二種辦法中的KVC修正屬性來完成
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持本站。
【iOS改動UITextField占位文字顏色的三種辦法】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!