首页 > 解决方案 > 如何在 UIButton 中将属性标题居中

问题描述

我正在尝试将 UIButton 的多行标题居中

我的按钮:

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

设置标题我正在使用一种方法,该方法采用字符串和字体大小并返回 NSAttributedString (顺便说一句,我无法修改它):

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

然后我设置按钮的标题:

aButton.setAttributedTitle(title, for: .normal)

文本仍然左对齐,但是,我做错了什么?谢谢

约束设置如下:

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

标签: iosswiftuibuttonnsattributedstring

解决方案


这是因为文本是属性字符串,设置后需要对齐文本。

您的解决方案将是:

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

通过设置属性字符串,而不是字符串,您将清除所有按钮的文本属性。

更好的解决方案是将对齐属性添加到属性字符串中


推荐阅读