Search code examples
iosswiftuibuttonnsattributedstring

How to center attributed title in UIButton


I am trying to center multiline title of a UIButton

my Button:

let aButton: UIButton = {
        let button = UIButton()
        button.titleLabel?.numberOfLines = 0
        button.titleLabel?.textAlignment = .center
        return button
    }()

to set the title I'm using a method that takes a string and font size and returns NSAttributedString (btw, I cannot modify that):

let title = markdownParser.parse(string: "my multiline string", fontSize: 15)

then I set up the button's title:

aButton.setAttributedTitle(title, for: .normal)

The text is still aligned to left, however, what is it that I'm doing wrong? Thanks

Constraints are set as below:

addSubview(aButton)
        aButton.snp.makeConstraints { maker in
            maker.center.equalToSuperview()
            maker.leading.trailing.equalToSuperview().inset(16)
        }

Solution

  • This is because the text is an attributed String, you will need to align the text after it has been set.

    Solution for you will be:

    aButton.setAttributedTitle(title, for: .normal)
    aButton.titleLabel?.textAlignment = .center
    

    By setting attributed String, instead of String, you are clearing all the button's text property.

    Nicer solution will be to add alignment attribute into the attributed String