【问题标题】:How to center attributed title in UIButton如何在 UIButton 中居中属性标题
【发布时间】:2021-06-07 12:57:42
【问题描述】:

我正在尝试将 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)
        }

【问题讨论】:

  • 通常按钮从其内容(标题和图像)中获取其内在内容大小,除非您以某种方式限制按钮的宽度,否则标题永远不会多行,它总是在一行.向我们展示代码,您如何添加按钮以查看?有什么限制?
  • 使用约束集编辑;目前我有 4 行文本,但左对齐

标签: ios swift uibutton nsattributedstring


【解决方案1】:

这是因为文本是一个属性化的String,设置好后需要对齐文本。

您的解决方案将是:

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

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

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

【讨论】:

  • 最终修改了将对齐添加到属性字符串的方法; aButton.titleLabel?.textAlignment = 为属性字符串设置文本后放置的 .center 不起作用
  • 是的,那是因为它是 UIButton 中的 UILabel。每次设置按钮标题时都会调用一些父类功能。
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2020-03-05
  • 2019-11-11
  • 2021-02-05
相关资源
最近更新 更多