[英]How to center attributed title in 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)
}
这是因为文本是属性字符串,设置后需要对齐文本。
您的解决方案将是:
aButton.setAttributedTitle(title, for: .normal)
aButton.titleLabel?.textAlignment = .center
通过设置属性字符串,而不是字符串,您将清除所有按钮的文本属性。
更好的解决方案是将 alignment 属性添加到属性字符串中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.