如何调用drawPlaceholderInRect

Rob*_*ert 2 cocoa-touch objective-c ios

我有一个自定义,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
}
Run Code Online (Sandbox Code Playgroud)

问题是文档说我不应该直接调用drawPlaceholderInRect,[self setNeedsDisplay];也不行.有任何想法吗?

Tho*_*ing 6

drawPlaceholderInRect:仅当文本字段实际包含占位符字符串时才调用该方法.(默认情况下不会)

尝试在Interface Builder中为文本字段设置占位符字符串.
还要确保在Custom Class字段中设置子.

更新:
我尝试重现问题中描述的问题,并遇到了这个问题.根据此Stack Overflow问题,这似乎是一个常见问题:https://stackoverflow.com/a/2581866/100848.

作为一种解决方法(至少在定位iOS> = 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];
Run Code Online (Sandbox Code Playgroud)