我在一个视图控制器中有2个UIButtons,它们有一定的固定宽度。因为应用程序需要支持多种语言,我需要能够调整他们的字体大小,以便文本将始终适合那个固定的宽度。
但是,当我使用: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)
}任何帮助都将不胜感激!
发布于 2020-07-15 08:14:05
只是遇到了同样的问题。更好的方法是将按钮放在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上面的代码遗漏了两件事:
驱动
希望这能有所帮助!
发布于 2016-11-29 22:30:07
一种可能的解决方案是比较两种字体大小,并使用较小的字体。未经测试的示例:
在viewDidLoad中
//let button1 = UIButton()
//var button2 = UIButton()
button1.titleLabel?.adjustsFontSizeToFitWidth = true
button2.titleLabel?.adjustsFontSizeToFitWidth = true在viewDidAppear中:
let size1: CGFloat = (button1.titleLabel?.font.pointSize)!
let size2: CGFloat = (button2.titleLabel?.font.pointSize)!
if size1.isLess(than: size2) {
button2.titleLabel?.font = button1.titleLabel?.font
} else if size2.isLess(than: size1) {
button1.titleLabel?.font = button2.titleLabel?.font
} https://stackoverflow.com/questions/40868023
复制相似问题