29

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?

almel
  • 7,178
  • 13
  • 45
  • 58

4 Answers4

71

You would want to write it like this:

myUITextObject.textAlignment = .center

(Edited to change from .Center to .center)

Klowne
  • 59
  • 8
Dave Wood
  • 13,143
  • 2
  • 59
  • 67
  • Note also that myUITextObject.contentVerticalAlignment can be set to .Top, .Center, .Fill or .Bottom to affect the vertical alignment – Dave Wood Jul 05 '14 at 17:57
  • 4
    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. – boidkan Oct 29 '14 at 22:24
  • Changed to myUITextObject.alignment = .center – Jack Mar 23 '18 at 21:03
2

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

myUITextObject.textAlignment = NSTextAlignmentCenter;

klcjr89
  • 5,862
  • 10
  • 58
  • 91
  • 5
    The code shown in this answer won't work in Swift (it would in Objective-C). –  Jul 05 '14 at 17:53
  • @Anna you're right, and I changed the correct answer to be Dave's – almel Jul 05 '14 at 17:55
  • @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. – almel Jul 05 '14 at 18:27
  • 1
    In Swift it would look like this: textField.textAlignment = NSTextAlignment.Center; – Gmeister4 Oct 12 '15 at 01:23
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,

Snoobie
  • 760
  • 2
  • 12
  • 30
0

Swift 5 2021

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