【问题标题】:Right align PlaceHolder text in UITextField在 UITextField 中右对齐 PlaceHolder 文本
【发布时间】:2013-08-28 06:26:08
【问题描述】:

我有一个文本右对齐的 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];
}

【问题讨论】:

    标签: iphone ios uitextfield alignment placeholder


    【解决方案1】:

    这是基于 Michael 解决方案的代码 sn-p。您应该创建文本字段的子类并添加以下方法。下面的方法基本上改变了占位符边界的 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;
    }
    

    【讨论】:

      【解决方案2】:

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

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

      为此,我建议使用以下方法:NSString 的[self placeholder] sizeWithFont: constrainedToSize:](假设[self placeholder] 是一个NSString),它将为您提供字符串的真实宽度。然后从文本字段框的右边缘减去宽度,就得到了需要从左边缘开始绘图的位置。

      【讨论】:

        【解决方案3】:

        我稍微增强了@Saikiran 的 sn-p,这对我有用:

        - (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];
        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-24
          • 1970-01-01
          • 2014-04-09
          • 2012-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多