在UITextField中右对齐占位文本

3
我有一个右对齐的UITextField。 我想改变占位符文本的颜色,所以我使用- (void)drawPlaceholderInRect:(CGRect)rect方法。它很奏效,但是现在占位符文本是左对齐的(文本仍然是右对齐的)。我猜可以添加一些代码来覆盖它,但我没有找到哪一个。谢谢!
- (void)drawPlaceholderInRect:(CGRect)rect
{
    [[UIColor redColor] setFill];
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
    [[self placeholder] drawInRect:rect withFont:font];
}
3个回答

3
这是基于Michael方案的代码片段。您需要创建文本字段的子类,并添加以下方法。下面的方法基本上会更改占位符边界框的x位置和宽度。
- (CGRect)placeholderRectForBounds:(CGRect)bounds{
    CGRect newbounds = bounds;
    CGSize size = [[self placeholder] sizeWithAttributes:
                       @{NSFontAttributeName: self.font}];
    int width =  bounds.size.width - size.width;
    newbounds.origin.x = width ;
    newbounds.size.width = size.width;
    return newbounds;
}

1
你发现"drawInRect"自动从左侧开始绘制。
你需要做的是调整传递给"drawInRect"的"rect",使得绘制文本的右边缘与UITextField矩形的右边缘相接。
为了做到这一点,我建议使用此方法: NSString的[self placeholder] sizeWithFont: constrainedToSize:] (假设[self placeholder]是一个NSString),它将给出字符串的真实宽度。然后从文本字段框的右边缘减去该宽度,就可以得到需要从其开始绘制的左边缘。

0

我稍微改进了@Saikiran的代码片段,这对我有效:

- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return self.editing ? ({CGRect bounds_ = [super placeholderRectForBounds:bounds];
        bounds_.origin.x    = bounds_.size.width
                              - ceilf(self.attributedPlaceholder.size.width)
                              + self.inset.x;
        bounds_.origin.y    = .5f * (.5f * bounds_.size.height
                                     - ceilf(self.attributedPlaceholder.size.height));
        bounds_.size.width  = ceilf(self.attributedPlaceholder.size.width);
        bounds_.size.height = ceilf(self.attributedPlaceholder.size.height);
        bounds_;
    }) : [super placeholderRectForBounds:bounds];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接