有時(shí),UITextField自帶的占位文字的顏色太淺或者不滿足需求,所以需要修改,而UITextField沒(méi)有直接的屬性去修改占位文字的顏色,所以只能通過(guò)其他間接方式去修改。
例如:系統(tǒng)默認(rèn)的占位文字顏色太淺

需要加深顏色,或者改變顏色
示例:

核心代碼
方法一:通過(guò)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:@"請(qǐng)輸入占位文字" attributes: @{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:textField.font }]; textField.attributedPlaceholder = attrString; [self.view addSubview:textField];方法二:通過(guò)KVC修改占位文字顏色
UITextField *textField1 = [[UITextField alloc] init]; textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH); textField1.borderStyle = UITextBorderStyleRoundedRect; textField1.placeholder = @"請(qǐng)輸入占位文字"; textField1.font = [UIFont systemFontOfSize:14]; // "通過(guò)KVC修改占位文字的顏色" [textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"]; [self.view addSubview:textField1];
方法三:通過(guò)重寫(xiě)UITextField的drawPlaceholderInRect:方法修改占位文字顏色
1、自定義一個(gè)TextField繼承自UITextField
2、重寫(xiě)drawPlaceholderInRect:方法
3、在drawPlaceholderInRect方法中設(shè)置placeholder的屬性
// 重寫(xiě)此方法-(void)drawPlaceholderInRect:(CGRect)rect { // 計(jì)算占位文字的 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}];}總結(jié):
1、當(dāng)我們使用純代碼創(chuàng)建UITextField時(shí),用第二種方法(KVC)修改占位文字顏色是最便捷的
2、當(dāng)我們使用XIB或者Storyboard創(chuàng)建UITextField時(shí),通過(guò)自定義UITextField,修改占位文字顏色是最適合的。
3、我們也可以在第三種重寫(xiě)方法中,通過(guò)結(jié)合第二種方法中的KVC修改屬性來(lái)實(shí)現(xiàn)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注