Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active August 15, 2016 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save T-Pham/165b50dec3866ed5d4134796f653730c to your computer and use it in GitHub Desktop.
Save T-Pham/165b50dec3866ed5d4134796f653730c to your computer and use it in GitHub Desktop.
Convenient Swift method to run a closure of UI-optimizing code on some devices selectively based on their logical height

The gist provides a convenient Swift method to run a closure of UI-optimizing code on some devices selectively based on their logical height. The usage examples show:

  • How to use the method to scale a view designed for iPhone 6+ to display on other devices. This is generally not recommended in production because scaling does not give good visual results.
  • Adjust a UIImageView's contentMode on iPhone 5 (SE, 5s, 5c, etc) and below.
//
// DeviceOptimizer.swift
//
// Created by Thanh Pham on 8/4/16.
//
import UIKit
struct DeviceOptimizer {
enum DeviceHeightType: CGFloat {
case iPhone4 = 640
case iPhone5 = 568
case iPhone6 = 667
case iPhone6Plus = 736
}
static func optimizeForDevicesWithHeight(comparator: (CGFloat, CGFloat) -> Bool, _ deviceHeightType: DeviceHeightType, @noescape closure: Void -> Void) {
guard comparator(UIScreen.mainScreen().bounds.height, deviceHeightType.rawValue) else {
return
}
closure()
}
}
DeviceOptimizer.optimizeForDevicesWithHeight(!=, .iPhone6Plus) {
let screenSize = UIScreen.mainScreen().bounds.size
let height = DeviceOptimizer.DeviceHeightType.iPhone6Plus.rawValue
view.bounds = CGRectMake(0, 0, screenSize.width / screenSize.height * height, height)
let scale = screenSize.height / height
view.transform = CGAffineTransformMakeScale(scale, scale)
}
DeviceOptimizer.optimizeForDevicesWithHeight(<=, .iPhone5) {
imageView.contentMode = .ScaleAspectFit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment