简体   繁体   中英

Right align PlaceHolder text in UITextField

I have a UITextField with the text right-aligned. I wanted to change the color of the placeholder text, so I use - (void)drawPlaceholderInRect:(CGRect)rect method. It works great BUT the placeholder text is left-aligned now (the text remains right-aligned). I guess I can add some code to override it but I didn't find which one. Thanks in advance !

- (void)drawPlaceholderInRect:(CGRect)rect
{
    [[UIColor redColor] setFill];
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
    [[self placeholder] drawInRect:rect withFont:font];
}

Here is the code snippet based on Michael solution. You should create subclass of text field and add the below method. Below method basically changes x-position and width of place holder bounds.

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

You've discovered that " drawInRect " is automagically drawing from the left edge going right.

What you need to do is adjust the " rect " passed to " drawInRect " to have left edge that allows the right edge of the drawn text to touch the right edge of your UITextField rect.

To do this, I'd recommend using this method: NSString's [self placeholder] sizeWithFont: constrainedToSize:] (assuming [self placeholder] is a NSString) which will give you the true width of the string. Then subtract the width from the right edge of the text field box and you have the left edge where you need to start your drawing from.

I enhanced @Saikiran's snippet a little, this works for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM