如何改變UITextField的placeholder的顏色

在項目中我們有時會遇到讓我們改變placeholder的顏色,簡單介紹一下改變placeholder的顏色的幾種方法

  1. 利用屬性字符串,UITextField有這樣一個屬性attributedPlaceholder,可以讓我們定制placeholder的屬性
    <pre>let placeHolderTextAttr = NSMutableAttributedString(string: "請輸入您的名字");
    placeHolderTextAttr.addAttributes([NSForegroundColorAttributeName:UIColor.redColor()], range: NSMakeRange(0, placeHolderTextAttr.length))
    self.textField.attributedPlaceholder = placeHolderTextAttr;
    </pre>

  2. 如果用xib或SB的話,可以在xib中設(shè)置user Defined Runtime Attributes
    keyPath設(shè)置成_placeholderLabel.textColor type設(shè)置成Color,需要注意的是,設(shè)置之前一定要先選中textField


    屏幕快照 2016-09-09 07.35.37.png
  3. 用extension和KVC去做,由于以上2種寫法只針對某一個textField,如果有多個textField需要設(shè)置的話,顯得比較麻煩,用extension的話就簡單多了
    <pre>
    extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
    get {
    return self.placeHolderColor
    }
    set {
    if let placeHolderLabel = self.valueForKey("placeholderLabel") as? UILabel {
    placeHolderLabel.textColor = newValue!;
    } ;
    }
    }
    }</pre>

  4. 在OC中extension是不能添加實現(xiàn)的這時我們可以用分類去實現(xiàn)這個功能
    <pre>
    @interface UITextField (SCPlaceHolder)
    @property (nonatomic,strong)IBInspectable UIColor *sc_placeHolderColor;
    @end
    @implementation UITextField (SCPlaceHolder)
    <code>-</code> (void)setSc_placeHolderColor:(UIColor *)sc_placeHolderColor{
    ((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor = sc_placeHolderColor;
    }
    <code>-</code> (UIColor *)sc_placeHolderColor{
    return ((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor;
    }
    @end
    </pre>

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

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

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