ios - 如何在 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
通过设置属性字符串,而不是字符串,您将清除所有按钮的文本属性。
更好的解决方案是将对齐属性添加到属性字符串中
推荐阅读
- python - 保存到表第一次但不是第二次会导致错误:SQLalchemy 中的 NOT NULL 约束失败
- vhdl - 制作单输入解复用器
- sql - 对某个值进行分组,以便下一行的空值位于前一行
- c++ - 用于定义具有可变参数的函数的嵌套#define 问题
- swiftui - Scrollview 不会滚动过去的带有偏移量的视图
- user-interface - 如何确定用于构建桌面应用程序 (Zoom) UI 的框架?
- python - 将熊猫数据框呈现为 html 后,最终 html 表中缺少列
- sql-server - SQL Server:从一个表复制到另一个 accountID 匹配的表
- javascript - 在反应中使用 REST API 的正确方法?
- azerothcore - 在突袭中将光环应用于玩家的正确方法是什么?