Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A static character prefix in UITextField

Is there a built-in way to add a character prefix to a UITextField like the screenshot below?

enter image description here

If no, what is the best, most straight-forward way to accomplish this? I am thinking the background property might be able to do this.

like image 561
pixelfreak Avatar asked Jul 01 '12 20:07

pixelfreak


People also ask

What is UITextField?

An object that displays an editable text area in your interface.

How to limit the number of characters in a UITextField?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).


2 Answers

Following on from Anne's code you can also do this directly in code without the UILabel in IB and UIView in code:

UILabel *poundLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
poundLabel.text = @"£";
[self.paymentAmount setLeftView:poundLabel];
[self.paymentAmount setLeftViewMode:UITextFieldViewModeAlways];
like image 122
Diziet Avatar answered Nov 14 '22 18:11

Diziet


Simply adding a gray UILabel on top of the UITextField does the trick:

001002

Note that the UILabel behaves like a background image, the entered text stays on top:

003

UPDATE

Additionally you can add some padding to the UITextField using the following code:

UIView *thePadding = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
theTextField.leftView = thePadding;
theTextField.leftViewMode = UITextFieldViewModeAlways;

This way the text cannot cover the prefix character.
Adjust the rect to make it working properly in your situation.

like image 32
Anne Avatar answered Nov 14 '22 18:11

Anne