我有一个自定义UITextField
,以便我得到一个自定义的占位符文字颜色,如答案所示。但是,我还想在运行时更改占位符文本的颜色,因此我创建了一个属性。
// Overide the placholder text color
- (void) drawPlaceholderInRect:(CGRect)rect
{
[self.placeholderTextColor setFill];
[self.placeholder drawInRect:rect
withFont:self.font
lineBreakMode:UILineBreakModeTailTruncation
alignment:self.textAlignment];
}
- (void) setPlaceholderTextColor:(UIColor *)placeholderTextColor
{
// To verify this is being called and that the placeholder property is set
NSLog(@"placeholder text: %@", self.placeholder);
_placeholderTextColor = placeholderTextColor;
[self setNeedsDisplay]; // This does not trigger drawPlaceholderInRect
}
问题是docs say I should not call drawPlaceholderInRect directly,而[self setNeedsDisplay];
不起作用。有什么想法吗?
答案 0 :(得分:6)
仅当文本字段实际包含占位符字符串时才调用drawPlaceholderInRect:
方法。 (默认不是这样)
尝试在Interface Builder中为文本字段设置占位符字符串 还要确保在自定义类字段中设置子类。
<强>更新强>
我尝试重现问题中描述的问题,并遇到了这个问题。根据此Stack Overflow问题,这似乎是一个常见问题:https://stackoverflow.com/a/2581866/100848。
作为一种解决方法(至少在定位iOS&gt; = 6.0时),您可以使用UITextField的attributionPlaceHolder:
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:@"asdf"];
NSDictionary* attributes = @{NSForegroundColorAttributeName:[UIColor redColor]};
[attributedString setAttributes:attributes range:NSMakeRange(0, [attributedString length])];
[self.textField setAttributedPlaceholder:attributedString];
答案 1 :(得分:4)
您也可以通过继承UITextField并覆盖drawPlaceholderInRect来实现这一目标
- (void) drawPlaceholderInRect:(CGRect)rect {
if (self.useSmallPlaceholder) {
NSDictionary *attributes = @{
NSForegroundColorAttributeName : kInputPlaceholderTextColor,
NSFontAttributeName : [UIFont fontWithName:kInputPlaceholderFontName size:kInputPlaceholderFontSize]
};
//center vertically
CGSize textSize = [self.placeholder sizeWithAttributes:attributes];
CGFloat hdif = rect.size.height - textSize.height;
hdif = MAX(0, hdif);
rect.origin.y += ceil(hdif/2.0);
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
else {
[super drawPlaceholderInRect:rect];
}
}
http://www.veltema.jp/2014/09/15/Changing-UITextField-placeholder-font-and-color/