Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
almel Avatar asked Jul 05 '14 17:07

almel


3 Answers

You would want to write it like this:

myUITextObject.textAlignment = .center

(Edited to change from .Center to .center)

like image 99
Dave Wood Avatar answered Oct 20 '22 01:10

Dave Wood


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

myUITextObject.textAlignment = NSTextAlignmentCenter;

like image 2
klcjr89 Avatar answered Oct 20 '22 01:10

klcjr89


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,

like image 1
Snoobie Avatar answered Oct 20 '22 02:10

Snoobie