简体   繁体   中英

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

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

文本域图像

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.

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 .

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

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 :-)

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.

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