简体   繁体   中英

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)
        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM