almel
almel

Reputation: 7938

How to center UITextField text in Swift

I have a UITextField object with the text property set to "hi". However these two lines have no affect on where "hi" is located

 myUITextObject.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
 myUITextObject.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center

Is this a bug in Swift? If so how do I go about logging this as a bug so Apple can fix it in the next Swift release?

Upvotes: 30

Views: 43668

Answers (4)

babatunde adewole
babatunde adewole

Reputation: 493

Swift 5 2021

yourTextField.attributedText = NSAttributedString(string: "String for textfield", attributes: [.paragraphStyle: paragraphStyle])

Upvotes: 0

Dave Wood
Dave Wood

Reputation: 13313

You would want to write it like this:

myUITextObject.textAlignment = .center

(Edited to change from .Center to .center)

Upvotes: 72

Snoobie
Snoobie

Reputation: 760

Another way to do it, is by using the storyboard.

In fact there is a Vertical and Horizontal Control that you can use for align your element inside the UITextField. In the case above that align the text to the top left:

enter image description here

Hope it helps,

Upvotes: 1

klcjr89
klcjr89

Reputation: 5902

What you're looking for is the textAlignment property; try this:

myUITextObject.textAlignment = NSTextAlignmentCenter;

Upvotes: 2

Related Questions