gpt4 book ai didi

ios - 使用 fit to width 时设置多个 UIButton 的字体大小相等

转载 作者:行者123 更新时间:2023-11-28 08:22:43 24 4
gpt4 key购买 nike

我在 View Controller 中有 2 个 UIButton,它们具有一定的固定宽度。因为该应用需要支持多种语言,所以我需要能够调整它们的字体大小,以便文本始终适合该固定宽度。

但是,当我使用:button.titleLabel?.adjustsFontSizeToFitWidth = true 时,一个按钮的字体大小会比另一个大。

因此,我需要两种字体大小都为它们的最小字体大小,这取决于适合宽度。

我发现了这个问题,但无法将其转换为 Swift:Adjust the font size to fit for several UIButton's so that they all have the same font size

我试过:

func customizeFontSize() {
button1.setTitle("text 1", for: .normal)
button2.setTitle("text 2", for: .normal)
let minFont1: Float = self.idealFontSize(for: button1)
let minFont2: Float = self.idealFontSize(for: button2)
let fontSize: Float = min(minFont1, minFont2)
let tailoredFont = button1.titleLabel!.font.withSize(CGFloat(fontSize))
self.button1.titleLabel!.font = tailoredFont
self.button2.titleLabel!.font = tailoredFont
}

func idealFontSize(for button: UIButton) -> Float {
let label = button.titleLabel!
let temp: Float = 10.0
let width: Float = Float(button.bounds.size.width) - temp
assert(button.bounds.size.width >= label.bounds.size.width)
let actualFontSize: CGFloat

//unavailable in swift
label.text!.size(with: label.font, minFontSize: label.minimumFontSize, actualFontSize: actualFontSize, forWidth: width, lineBreakMode: label.lineBreakMode)
debug("idealFontSizeForButton %f", actualFontSize)

return Float(actualFontSize)
}

如有任何帮助,我们将不胜感激!

最佳答案

刚刚遇到了同样的问题。发现更好的方法是将按钮放在 UIStackView 中并将其分布模式设置为比例。这样,如果没有足够的空间来容纳全尺寸内容,每个元素都会按比例缩小。

示例代码:

let stackview = UIStackView(arrangedSubviews: [leftButton, rightButton])
stackview.translatesAutoresizingMaskIntoConstraints = false
stackview.spacing = 16
stackview.axis = .horizontal
stackview.distribution = .fillProportionally
stackview.alignment = .center
addSubview(stackview)
stackview.widthAnchor.constraint(lessThanOrEqualToConstant:
UIScreen.main.bounds.width - 80).isActive = true

上面的代码遗漏了两件事:

  1. 将设置 stackview 在 x 和 y 轴上的位置的布局约束
  2. 适当宽度的 anchor - 应在 layoutSubviews 上设置或由其他一些自动布局约束驱动

希望这对您有所帮助!

关于ios - 使用 fit to width 时设置多个 UIButton 的字体大小相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40868023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com