【问题标题】:UIButton - setTitle vs setAttributedTitle - button not resized with laterUIButton - setTitle 与 setAttributedTitle - 按钮未调整大小
【发布时间】:2021-12-26 00:32:58
【问题描述】:

我正在为 UIButton 动态设置文本。 如果我使用setTitle("\u{25CF} Hello world", for: .normal),按钮会调整大小,我可以看到整个文本(“● Hello world”)

但是,当我使用setAttributedTitle 时,按钮不会调整大小并且文本会用点缩短(如“● He...ld”)

let desc = NSMutableAttributedString(string: "\u{25CF}", attributes: [NNSAttributedString.Key.font: UIFont.systemFont(ofSize: UIFont.buttonFontSize * 0.4, weight: .light)])
desc.append(NSAttributedString(string: " Hello world"))
self.setAttributedTitle(desc, for: .normal)

我的按钮是通过编程设置的

button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.light)
button.titleLabel?.numberOfLines = 1
button.contentEdgeInsets =  UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
button.translatesAutoresizingMaskIntoConstraints = false

按钮通过addArrangedSubview 添加到UIStackView。按钮没有附加任何约束。

在设置标题之前,我在父视图上调用layoutIfNeeded()

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    解决方案是为附加的属性文本指定字体大小

    let desc = NSMutableAttributedString(string: "\u{25CF}", attributes: [NNSAttributedString.Key.font: UIFont.systemFont(ofSize: UIFont.buttonFontSize * 0.4, weight: .light)])
    desc.append(NSAttributedString(string: " Hello world"), attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .light)]))
    self.setAttributedTitle(desc, for: .normal)
    

    【讨论】:

      猜你喜欢
      • 2017-03-21
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      相关资源
      最近更新 更多