3
votes

How to create UITextField with placeholder to the left and edited text to the right?

textfield image

UITextField itself does not allow using its properties to put placeholder and edited text to different sides. Try to set it in the storyboard -> attributes inspector -> alignment. They are both to the left or both the right. There is no special alignment only for placeholder or only for the text.

4

4 Answers

7
votes

To do this you should add a UILabel to the UITextField which is not editable and doesn't allow touches. Then set the text alignment on the UITextField to NSTextAlignmentRight.

5
votes

First, set the text alignment to the right:

    [textField setTextAlignment:NSTextAlignmentRight];

Fir the placeholder, you can add it as a subview, or use the leftView property:

    [textField setLeftView:<your label here>];
1
votes

I just created a custom UITextField subclass that does this. To use it simply create your UITextField on the Storyboard or Xib... put a placeholder text in there, set the text fields class as OBSTextFieldWithLabel and then you can use the following code:

@interface OBSTextFieldWithLabel : UITextField
@end

@implementation OBSTextFieldWithLabel
  - (void)awakeFromNib
  {
    [super awakeFromNib];

    NSString *labelText = [self placeholder];
    self.placeholder = nil;
    CGRect labelFrame = CGRectMake(20, 10, 150, 15);
    UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:labelFrame];
    [placeholderLabel setFont:[UIFont systemFontOfSize:12]];
    [placeholderLabel setTextColor:[UIColor lightGrayColor]];
    [placeholderLabel setText:labelText];
    [self addSubview:placeholderLabel];
    [self setTextAlignment:NSTextAlignmentRight];
  }
@end

This is probably not 100% perfect as the label size is not dynamically set and all...but it should get you up and running and it works :-)

0
votes

I've written a control that might help you. Essentially it's intended for highlighting a UITextField while it is being edited, but it also has a mechanism for a placeholder on the left, as you can see in the screenshots.

https://www.cocoacontrols.com/controls/sahighlightedtextfield

Hope this points you in the right direction.