【问题标题】:Auto change font size for different iPhone devices自动更改不同 iPhone 设备的字体大小
【发布时间】:2018-05-01 04:10:17
【问题描述】:

是否可以为整个应用程序根据不同的 iPhone 设备大小设置不同的UILabels 字体大小?

【问题讨论】:

    标签: ios fonts


    【解决方案1】:

    我为此目的使用每个控件的自定义类

        class Label: UILabel {
    
        @IBInspectable var iPhoneFontSize:CGFloat = 0 {
            didSet {
                overrideFontSize(fontSize: iPhoneFontSize)
            }
        }
    
        @IBInspectable
        public var cornerRadius: CGFloat = 2.0 {
            didSet {
                self.layer.cornerRadius = self.cornerRadius
            }
        }
    
        @IBInspectable
        public var borderWidth: CGFloat = 0 {
            didSet {
                self.layer.borderWidth = self.borderWidth
            }
        }
    
        @IBInspectable
        public var borderColor: UIColor = .clear {
            didSet {
                self.layer.borderColor = self.borderColor.cgColor
            }
        }
    
       private func overrideFontSize(fontSize:CGFloat){
            let currentFontName = self.font.fontName
            var calculatedFont: UIFont?
            let bounds = UIScreen.main.bounds
            let height = bounds.size.height
            switch height {
            case 480.0: //Iphone 3,4,SE => 3.5 inch
                calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.7)
                self.font = calculatedFont
                break
            case 568.0: //iphone 5, 5s => 4 inch
                calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.8)
                self.font = calculatedFont
                break
            case 667.0: //iphone 6, 6s, 7, 7s => 4.7 inch
                calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.9)
                self.font = calculatedFont
                break
            case 736.0: //iphone 6+, 6s+, 7+, 7s+ => 5.5 inch
                calculatedFont = UIFont(name: currentFontName, size: fontSize)
                self.font = calculatedFont
                break
            default: // New devices
                calculatedFont = UIFont(name: currentFontName, size: fontSize)
                self.font = calculatedFont
                break
            }
    
        }
    }
    

    然后在 Storyboard 中为最高分辨率设置 iPhoneFontSize 属性值,如下面的屏幕截图所示。

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2020-08-21
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多