varun
varun

Reputation: 317

How to align text in UITextField?

Is it possible to align placeholder in the middle of a UITextField? And when we start editing it should it start from left corner of UITextField? I am new to iOS.

Upvotes: 4

Views: 12116

Answers (3)

Noam Segev
Noam Segev

Reputation: 415

Swift 3.0 ... Swift 5.5

    textField.textAlignment = .center

Upvotes: 2

bsarrazin
bsarrazin

Reputation: 4040

Start by setting textField.textAlignment = NSTextAlignmentCenter. Your best bet is to implement the use of the UITextFieldDelegate protocol to know when the user is tapping inside your text field. Once the user has tapped inside your text field change the property to textField.textAlignment = NSTextAlignmentLeft if you want the alignment to go back to the left. Additionally, using the same protocol, when the user taps out or the focus leaves your text field, set the property back to textField.textAlignment = NSTextAlignmentCenter.

Upvotes: 2

Nimit Parekh
Nimit Parekh

Reputation: 16864

Here is the sample code for that.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    txtList.textAlignment = NSTextAlignmentCenter;
}
// This method is called once we click inside the textField
-(void)textFieldDidBeginEditing:(UITextField *)textField{

    txtList.textAlignment = NSTextAlignmentLeft;
}

Don't forgot to give delegate of UITextField.

Upvotes: 9

Related Questions