右键将PlaceHolder文本对齐到UITextField中

时间:2013-08-25 19:15:49

标签: iphone ios uitextfield alignment placeholder

我有一个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 个答案:

答案 0 :(得分:2)

以下是基于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 :(得分:0)

您发现“drawInRect”会自动从左边缘向右绘制。

您需要做的是调整传递给“rect”的“drawInRect”以使左边缘允许绘制文本的右边缘触及UITextField矩形的右边缘。

为此,我建议使用此方法:NSString的[self placeholder] sizeWithFont: constrainedToSize:](假设[self placeholder]是NSString),它将为您提供字符串的真实宽度。然后从文本字段框的右边缘减去宽度,并在左边缘处开始绘制。

答案 2 :(得分: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];
}
相关问题