iOS Different Font Sizes within Single Size Class for Different Devices

前端 未结 7 1573
死守一世寂寞
死守一世寂寞 2020-12-01 05:32

In iOS 8, we can design a different UI layout for each size class. The issue I\'m facing is, I\'ve designed a layout for Compact Width and Regular Height (size class for all

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 06:10

    I'm handling it in a project in Swift 3+ using a UILabel Custom class, UILabel extension, and UIDevice extension as generic solution.

    UIDevice extension to get screenType:

    public extension UIDevice {
    
        var iPhone: Bool {
            return UIDevice().userInterfaceIdiom == .phone
        }
    
        enum ScreenType: String {
            case iPhone4
            case iPhone5
            case iPhone6
            case iPhone6Plus
            case iPhoneX
            case Unknown
        }
    
        var screenType: ScreenType {
            guard iPhone else { return .Unknown}
            switch UIScreen.main.nativeBounds.height {
            case 960:
                return .iPhone4
            case 1136:
                return .iPhone5
            case 1334:
                return .iPhone6
            case 2208:
                return .iPhone6Plus
            case 2436:
                return .iPhoneX
            default:
                return .Unknown
            }
        }
    
    }
    

    Following is the UILabel extension that uses screenType to adjust font size. adjustsFontSizeToFitDevice method could be added in UILabel custom class too, but I've put it in UILabel extension to make it accessible from all types of UILabel instances.

    The constant "2" used in adjustsFontSizeToFitDevice method can be changed to any desired number. My logic is to consider iPhone 6/7/8 as default resolution, and give suitable font size (in Storyboard) to each label for that resolution. Then, I'm adding 2 points for iPhone X and iPhone 6/7/8 Plus, whereas subtracting 2 points for iPhone 4/5.

    extension UILabel {
    
        func adjustsFontSizeToFitDevice() {
    
            switch UIDevice().screenType {
            case .iPhone4, .iPhone5:
                font = font.withSize(font.pointSize - 2)
                break
            case .iPhone6Plus, .iPhoneX:
                font = font.withSize(font.pointSize + 2)
                break
            default:
                font = font.withSize(font.pointSize)
            }
        }
    
    }
    

    Finally a UILabel custom class to apply font adjustment to all labels that are sub-classed from MyCustomLabel.

    class MyCustomLabel: UILabel {
    
        // MARK: - Life Cycle Methods
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            adjustsFontSizeToFitDevice()
        }
    
    }
    

    Usage: In Storyboard, sub-class all those instances of UILabel from MyCustomLabel whose font size needs to be adjusted according to device size.

提交回复
热议问题