【问题标题】:Set titleLabel according to UIButton height根据UIButton高度设置titleLabel
【发布时间】:2018-04-03 06:18:58
【问题描述】:

我处于一种情况,我想根据 UIButton 的高度设置 UIButton 元素的 titleLabel 的字体大小,所以这是我的设置:

let button: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("title", for: [])
    button.titleLabel?.minimumScaleFactor = 0.5
    button.titleLabel?.numberOfLines = 1
    button.titleLabel?.adjustsFontSizeToFitWidth = true
    button.titleLabel?.lineBreakMode = .byClipping
    return button
}()

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(self.button)

    self.button.bottomAnchor.constraint(equalTo: self.someElement.topAnchor, constant: 0).isActive = true
    self.button.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.33).isActive = true
    self.button.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.1).isActive = true
    self.button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0).isActive = true
}

会发生什么?

按钮宽度设置为视图宽度的 33% -> 好

按钮高度设置为视图高度的 10% -> 好

按钮 titleLabel 字体大小保持较小且不随按钮高度缩放... -> 不好

谁能给我解释一下?

【问题讨论】:

    标签: swift layout uibutton constraints nslayoutconstraint


    【解决方案1】:

    使用按钮高度缩放标签的一种可能解决方案是在 viewDidAppear 方法中调整字体大小。重要的是,您在此处而不是在 viewDidLoad 中执行此操作,因为在 viewDidLoad 中尚不知道按钮高度。

    以下代码片段应将按钮的字体大小缩放为按钮高度的一半:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // If you use a custom font, you have to replace systemFont with it
        button.titleLabel?.font = UIFont.systemFont(ofSize: button.frame.height * 0.5)
    }
    

    如果您的标题变得很长,它会被缩小以适应按钮的宽度(因为您已将 adjustsFontSizeToFitWidth 设置为 true)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2021-12-11
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      相关资源
      最近更新 更多