ios textfield 修改 placeholder color 顏色

UITextField修改placeholder color有很多種方式,但選擇哪一種看你自己,有一些方法並不建議,同時希望大家分享沒有摘錄的方法,tks

方法一(不推薦):

[_textPhone setValue:[UIColor whiteColor]
                    forKeyPath:@"_placeholderLabel.textColor"];

最直接一句話搞定,使用KVC模式直接設置TestField的私有屬性的值。沒錯,_placeholderLabel是一個私有的屬性,使用這種方式雖然簡單但並不是很好的做法,如果Apple修改(雖然至今沒有修改)了該屬性名後,會在之後的運行中遭遇崩潰,而編譯器卻無法識別。

有人說使用KVC修改私有屬性可能提交 app store審覈不通過,但也有人說能通過,自己試試吧~


方法二(不推薦):


意思同方法一


方法三:

UIColor *color = [UIColor whiteColor];
_textPhone.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_textPhone.placeholder attributes:@{NSForegroundColorAttributeName: color}];
使用UITextField的共有屬性attributedPlaceholder,妥妥的,雖然代碼略長~


方法四:

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    UIColor *color = [UIColor whiteColor];
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName: color}];
//    以下注釋的方法,在ios7後被放棄
//    [[UIColor whiteColor] setFill];
//    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
//
    
}

創建一個類繼承UITextField,並重寫該方法,使用該類即可,略麻煩,但如果是公用textField,推薦這種方法,可以添加更多設置。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章