gpt4 book ai didi

swift - 根据UIButton高度设置titleLabel

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:04 25 4
gpt4 key购买 nike

我现在的情况是,我想根据 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
}

会发生什么?

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

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

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

有人能给我解释一下吗?

最佳答案

使用按钮高度缩放标签的一种可能解决方案是在 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)。

关于swift - 根据UIButton高度设置titleLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876849/

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