Custom Font Sizing in Xcode 6 Size Classes not working properly with Custom Fonts

前端 未结 14 1292
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 17:42

Xcode 6 has a new feature where fonts and font sizes in UILabel, UITextField, and UIButton can be s

14条回答
  •  醉酒成梦
    2020-11-29 18:29

    After trying everything, I eventually settled on a combination of the above solutions. Using Xcode 7.2, Swift 2.

    import UIKit
    
    class LabelDeviceClass : UILabel {
    
        @IBInspectable var iPhoneSize:CGFloat = 0 {
            didSet {
                if isPhone() {
                    overrideFontSize(iPhoneSize)
                }
            }
        }
    
        @IBInspectable var iPadSize:CGFloat = 0 {
            didSet {
                if isPad() {
                    overrideFontSize(iPadSize)
                }
            }
        }
    
        func isPhone() -> Bool {
            // return UIDevice.currentDevice().userInterfaceIdiom == .Phone
            return !isPad()
        }
    
        func isPad() -> Bool {
            // return UIDevice.currentDevice().userInterfaceIdiom == .Pad
            switch (UIScreen.mainScreen().traitCollection.horizontalSizeClass, UIScreen.mainScreen().traitCollection.verticalSizeClass) {
            case (.Regular, .Regular):
                return true
            default:
                return false
            }
        }
    
        func overrideFontSize(fontSize:CGFloat){
            let currentFontName = self.font.fontName
            if let calculatedFont = UIFont(name: currentFontName, size: fontSize) {
                self.font = calculatedFont
            }
        }
    
    }
    
    • @IBInspectable lets you set the font size in the Storyboard
    • It uses a didSet observer, to avoid the pitfalls from layoutSubviews() (infinite loop for dynamic table view row heights) and awakeFromNib() (see @cocoaNoob's comment)
    • It uses size classes rather than the device idiom, in hopes of eventually using this with @IBDesignable
    • Sadly, @IBDesignable doesn't work with traitCollection according to this other stack article
    • The trait collection switch statement is performed on UIScreen.mainScreen() rather than self per this stack article

提交回复
热议问题