09-占位文字顏色

修改占位文字顏色有四種方法:

第一種:(最簡單)一般用這個

修改內(nèi)部占位文字Label的文字顏色

[textField setValue:[UIColor grayColor] forKeyPath:@"placeholderLabel.textColor"];

第二種:使用attributedPlaceholder

// 設置占位文字內(nèi)容
@property(nullable, nonatomic,copy) NSString *placeholder;
// 設置帶有屬性的占位文字, 優(yōu)先級 > placeholder
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder;
// 設置占位文字顏色
 NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
 attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
 self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attributes];

第三種:重寫- (void)drawPlaceholderInRect:(CGRect)rect;

第四種:利用分類為UITextField添加占位文字屬性--->推薦,一勞永逸
注意:
問題:為什么要先確保有占位文字,再設置占位文字顏色?
結果:若先設置占位文字顏色,在設置占位文字,就會無效果。
原因:不設置文字,就不會創(chuàng)建label這個控件,那么占位文字也就拿不到了,又如何設置占位文字顏色呢.

/**  占位文字顏色 **/
@property (nonatomic ,strong) UIColor *placeholderColor;
#import "UITextField+ZSExtension.h"

static NSString *const ZSPlaceholderColorKey = @"placeholderLabel.textColor";
@implementation UITextField (ZSExtension)

-(void)setPlaceholderColor:(UIColor *)placeholderColor
{
    // 點擊時占位文字的顯示
    BOOL change = NO;
    
    //保證有占位文字
    if (self.placeholder == nil) {
        self.placeholder = @"";
    }
    // 占位文字顏色
    [self setValue:placeholderColor forKeyPath:ZSPlaceholderColorKey];
    
    // 恢復原狀
    if (change) {
        self.placeholderColor = nil;
    }
}

-(UIColor *)placeholderColor
{
    return [self valueForKeyPath:ZSPlaceholderColorKey];
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容