2

我有一个自定义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
}

问题是文档说我不应该直接调用 drawPlaceholderInRect,并且[self setNeedsDisplay];不起作用。有任何想法吗?

4

3 回答 3

6

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

尝试在 Interface Builder 中为您的文本字段设置占位符字符串。
还要确保在自定义类字段中设置您的子类。

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

作为一种解决方法(至少在针对 iOS >= 6.0 时),您可以使用 UITextField 的属性化位置:

NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:@"asdf"];
NSDictionary* attributes = @{NSForegroundColorAttributeName:[UIColor redColor]};
[attributedString setAttributes:attributes range:NSMakeRange(0, [attributedString length])];
[self.textField setAttributedPlaceholder:attributedString];
于 2013-06-02T12:23:37.667 回答
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/

于 2014-09-15T06:19:49.780 回答
0

添加类级别变量:

float forcePlaceHolderDraw;

将此代码添加到您的子类中:

- (CGRect)placeholderRectForBounds:(CGRect)bounds {
if (forcePlaceHolderDraw == 0) {
        forcePlaceHolderDraw = 0.000001;
    } else {
        forcePlaceHolderDraw = 0;
    }
    return CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width + forcePlaceHolderDraw, bounds.size.height);
}

我认为鉴于新旧框架相同,强制绘制不起作用

于 2021-08-29T17:37:22.753 回答