設(shè)置UITextField的占位文字顏色三種方式
1>KVC修改 如果不先設(shè)置占位文字, 占位文字的顏色是不管用的:
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
textField.placeholder = @"設(shè)置了占位文字內(nèi)容以后, 才能設(shè)置占位文字的顏色";
textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
2>通過(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];
3>通過(guò)重寫UITextField的drawPlaceholderInRect:方法修改占位文字顏色
步驟:
- 1.自定義一個(gè)TextField繼承自UITextField
- 2.重寫drawPlaceholderInRect:方法
- 3.在drawPlaceholderInRect方法中設(shè)置placeholder的屬性
-(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}];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者