前言
最近學了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有所幫助,如果有疑問大家可以留言交流。