Search code examples
iosobjective-cuibuttoninterface-builder

How to make UIButton's text alignment center? Using IB


I can't set the title of UIButton using IB as center. My title is multi line.
It is giving like this one
enter image description here

But I want like this one
enter image description here

I have given space in this but I don't want to do that. As it is not aligned exactly for some cases and I know there is a property of UILabel to set the alignment but I don't want to write a code for that.. just want to set everything from IB.

Thanks


Solution

  • Solution1

    You can set the key path in the storyboard

    Set the text to your multiline title e.g. hello + multiline

    You need to press + to move text to next line.

    enter image description here

    Then add the key path

    titleLabel.textAlignment as Number and value 1, 1 means NSTextAlignmentCenter
    titleLabel.numberOfLines as Number and value 0, 0 means any number of lines

    enter image description here

    This will not be reflected on IB/Xcode, but will be in centre at run time (device/simulator)

    If you want to see the changes on Xcode you need to do the following: (remember you can skip these steps)

    1. Subclass the UIButton to make the button designable:

      import UIKit
      @IBDesignable class UIDesignableButton: UIButton {}
      

    2. Assign this designable subclass to the buttons you're modifying:

    Showing how to change the class of the button using Interface Builder

    1. Iff done right, you will see the visual update in IB when the Designables state is "Up to date" (which can take several seconds):

    Comparing the designable and default button in Interface Builder



    Solution2

    If you want to write the code, then do the long process

    1.Create IBOutlet for button
    2.Write code in viewDidLoad

    btn.titleLabel.textAlignment = .Center
    btn.titleLabel.numberOfLines = 0
    


    Solution3

    In newer version of xcode (mine is xcode 6.1) we have property attributed title
    Select Attributed then select the text and press centre option below

    P.S. The text was not coming multiline for that I have to set the

    btn.titleLabel.numberOfLines = 0

    enter image description here