ios - 在堆栈 View 中调整 UIButtons 中的文本大小

标签 ios swift uikit

我正在根据 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/

相关文章:

ios - 点击搜索按钮后,使搜索栏中的取消按钮处于事件状态

ios - 如何使用现有的导航 Controller 从 swiftui 导航到 viewcontroller

ios - xib文件中的uiview大小不正常

ios - Monotouch.Dialog 和 iAds

ios - Pixate 可以为 UIAlertView 设置样式吗?

ios - swift 中的 "as string"和 "stringvalue"有什么区别?

ios - 不确定在代码中放置 storageRef.downloadURL 的位置

swift - 如何创建一个过滤器,对 SQLite.Swift 执行相当于 WHERE ... IN 的 SQL 操作

ios - UITextView 由于行数和字符数限制文本

iphone - 渐变纹理背景