iOS-改變UITextField(純代碼 /xib) 中的Placeholder顏色的幾種方法

轉自:http://blog.csdn.net/mazy_ma/article/details/51775670

有時,UITextField自帶的佔位文字的顏色太淺或者不滿足需求,所以需要修改,而UITextField沒有直接的屬性去修改佔位文字的顏色,所以只能通過其他間接方式去修改。

例如:系統默認的佔位文字顏色太淺 
這裏寫圖片描述

需要加深顏色,或者改變顏色 
示例: 
這裏寫圖片描述


方法一:通過attributedPlaceholder屬性修改佔位文字顏色

    CGFloat viewWidth  = self.view.bounds.size.width;
    CGFloat textFieldX = 50;
    CGFloat textFieldH = 30;
    CGFloat padding    = 30;

    UITextField *textField = [[UITextField alloc] init];
    textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH);
    textField.borderStyle = UITextBorderStyleRoundedRect; // 邊框類型
    textField.font = [UIFont systemFontOfSize:14];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"請輸入佔位文字" attributes:
    @{NSForegroundColorAttributeName:[UIColor redColor],
                 NSFontAttributeName:textField.font
         }];
    textField.attributedPlaceholder = attrString;
    [self.view addSubview:textField];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

方法二:通過KVC修改佔位文字顏色

    UITextField *textField1 = [[UITextField alloc] init];
    textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.placeholder = @"請輸入佔位文字";
    textField1.font = [UIFont systemFontOfSize:14];
    // "通過KVC修改佔位文字的顏色字體"
    [textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];    [textField1setValue:[UIFontsystemFontOfSize:20]forKeyPath:@"_placeholderLabel.font”];
    [self.view addSubview:textField1];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法三:xib
適用於在Xib中添加的UITextField


方法四四:通過重寫UITextField的drawPlaceholderInRect:方法修改佔位文字顏色 

1、自定義一個TextField繼承自UITextField 
2、重寫drawPlaceholderInRect:方法 
3、在drawPlaceholderInRect方法中設置placeholder的屬性 

// 重寫此方法
-(void)drawPlaceholderInRect:(CGRect)rect {
    // 計算佔位文字的 Size
    CGSize placeholderSize = [self.placeholder sizeWithAttributes:
                              @{NSFontAttributeName : self.font}];

    [self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:
    @{NSForegroundColorAttributeName : [UIColor blueColor],
                 NSFontAttributeName : self.font}];
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

總結: 
1、當我們使用純代碼創建UITextField時,用第二種方法(KVC)修改佔位文字顏色是最便捷的 
2、當我們使用XIB或者Storyboard創建UITextField時,通過自定義UITextField,修改佔位文字顏色是最適合的。 
3、我們也可以在第三種重寫方法中,通過結合第二種方法中的KVC修改屬性來實現

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