5

I want my button title to be centered and simply selected word-wrap in the Attributes Inspector to have two lines.

But the second line is not displayed centered but starts at the same position as the first line (the first line is longer).

How can I center both lines? (I'm using Swift.)

maidi
  • 3,219
  • 6
  • 27
  • 55

1 Answers1

11

You cannot set the text alignment of UIButton in interface builder. Create and connect an IBOutlet for the said button in interface builder, and use the following code in viewDidLoad method of the view controller.

ibOutletOfButton.titleLabel.textAlignment = NSTextAlignment.Center;

I hope it helps!:-)

Suran
  • 1,209
  • 1
  • 17
  • 21
  • Thanks for your answer, but when I try it I get the error: "UILabel? does not have a member named 'textAlignment'". – maidi Apr 08 '15 at 13:08
  • @maidi, That is weird because UILabel has a property called textAlignment. Please see the link below; https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/index.html#//apple_ref/occ/instp/UILabel/textAlignment – Suran Apr 08 '15 at 13:31
  • I tried again and it worked now, I had to type a '?' after 'titleLabel', thanks :) – maidi Apr 08 '15 at 14:51
  • Sorry about the '?', I'm not familiar with swift. Anyway, glad it helped. :-) – Suran Apr 09 '15 at 06:37