我正在根据 viewDidLoad
上的设备宽度调整 4 个相同类型按钮中的文本大小。它们处于水平堆栈 View 中。有什么方法可以更优雅地做到这一点?
// resize main buttons
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
if screenWidth <= 320 {
mainLockButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
mainUnlockButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
mainSplitButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
mainRoundButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
} else if screenWidth <= 375 {
mainLockButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
mainUnlockButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
mainSplitButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
mainRoundButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
} else {
mainLockButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
mainUnlockButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
mainSplitButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
mainRoundButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
}
最佳答案
不完美,但看起来好多了
let screenWidth = UIScreen.main.bounds.width
let buttons = [mainLockButton, mainUnlockButton, mainSplitButton, mainRoundButton]
buttons.forEach {
if screenWidth <= 320 {
$0.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
} else if screenWidth <= 375 {
$0.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
} else {
$0.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
}
}
关于ios - 在堆栈 View 中调整 UIButtons 中的文本大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951395/