How to center UITextField text in Swift
Asked Answered
C

4

30

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?

Counterespionage answered 5/7, 2014 at 17:35 Comment(1)
@dasdom yes, and that did not workCounterespionage
C
73

You would want to write it like this:

myUITextObject.textAlignment = .center

(Edited to change from .Center to .center)

Cliffhanger answered 5/7, 2014 at 17:52 Comment(3)
Note also that myUITextObject.contentVerticalAlignment can be set to .Top, .Center, .Fill or .Bottom to affect the vertical alignmentCliffhanger
This only centers the text horizontally and myUITextObject.contentVerticalAlignment is not a thing anymore. Any ideas how to achieve vertical centering without doing a weird offset hack.Yaron
Changed to myUITextObject.alignment = .centerNatachanatal
D
2

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

myUITextObject.textAlignment = NSTextAlignmentCenter;

Delagarza answered 5/7, 2014 at 17:40 Comment(4)
The code shown in this answer won't work in Swift (it would in Objective-C).Traweek
@Anna you're right, and I changed the correct answer to be Dave'sCounterespionage
@Anna just curious, why did the code I first pasted in not work, from other SO posts it appeared like that was the way to do it. And having two different ways of doing the exact same thing seems strange.Counterespionage
In Swift it would look like this: textField.textAlignment = NSTextAlignment.Center;Mckeown
Z
1

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,

Zendavesta answered 31/5, 2016 at 16:35 Comment(0)
T
0

Swift 5 2021

yourTextField.attributedText = NSAttributedString(string: "String for textfield", attributes: [.paragraphStyle: paragraphStyle])
Thereupon answered 3/3, 2021 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.