媒介
比來學了UITextField控件, 感到在外面設置占位符異常好, 給用戶提醒信息, 因而就在想占位符的字體和色彩能不克不及轉變呢?上面是小編的一些簡略的完成,有須要的同伙們可以參考。
修正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外部placeholderLaber的色彩
[textField setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];
以下是具體的完成進程
給定場景,如在注冊登錄中,要修正手機號和暗碼TextField的placeholder的文字色彩。
後果比較

應用前

應用後
應用attributedPlaceholder
自界說GYLLoginRegisterTextField類,繼續自UITextField;完成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辦法,後續雷同
代碼以下:
#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外部placeholderLaber的色彩
應用KVC機制,找到UITextField外部的修正站位文字色彩的屬性: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辦法。
總結
以上就是這篇文章的全體內容了,願望能對年夜家開辟IOS有所贊助,假如有疑問年夜家可以留言交換。
【iOS中修正UITextField占位符字體色彩的辦法總結】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!