调整堆栈视图中UIButtons中的文本大小

时间:2018-06-20 15:04:59

标签: ios swift uikit

我正在根据viewDidLoad上的设备宽度来调整4个相同类型按钮的文本大小。它们处于水平堆栈视图中。有什么方法可以更优雅地做到这一点?

// 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)
        }

请不要无缘无故地投票给我:(我真的在寻求帮助。

2 个答案:

答案 0 :(得分:1)

不完美,但看起来要好得多

  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)
    }
  }

答案 1 :(得分:1)

var fontSize: CGFloat {
    let screenWidth = UIScreen.main.bounds.width
    switch screenWidth {
    case _ where screenWidth <= 320: return 12
    case _ where screenWidth <= 375: return 13
    default: return 14
    }
}

stackView.arrangedSubviews.forEach {
    if let button = $0 as? UIButton {
        button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: .medium)
    }
}