How to detect iPhone 5 (widescreen devices)?

前端 未结 24 1303
我寻月下人不归
我寻月下人不归 2020-11-22 00:50

I\'ve just upgraded to XCode 4.5 GM and found out that you can now apply the \'4\" Retina\' size to your view controller in the storyboard.

Now if I want to create a

24条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 01:16

    This has been answered a hundred times but this solution worked the best for me and helped address the issue when new devices are introduced and I don't have a size defined.

    Swift 5 Helper:

    extension UIScreen {
        func phoneSizeInInches() -> CGFloat {
            switch (self.nativeBounds.size.height) {
            case 960, 480:
                return 3.5  //iPhone 4
            case 1136:
                return 4    //iPhone 5
            case 1334:
                return 4.7  //iPhone 6
            case 2208:
                return 5.5  //iPhone 6 Plus
            case 2436:
                return 5.8  //iPhone X
            case 1792:
                return 6.1  //iPhone XR
            case 2688:
                return 6.5  //iPhone XS Max
            default:
                let scale = self.scale
                let ppi = scale * 163
                let width = self.bounds.size.width * scale
                let height = self.bounds.size.height * scale
                let horizontal = width / ppi, vertical = height / ppi
                let diagonal = sqrt(pow(horizontal, 2) + pow(vertical, 2))
                return diagonal
            }
        }
    }
    

    This is because it's easy to memorize a phone's inch sizes, like, "5.5 inch" or "4.7 inch" device but difficult to remember the exact pixel sizes.

    if UIScreen.main.phoneSizeInInches() == 4 {
      //do something with only 4 inch iPhones
    }
    

    This also gives you the opportunity to do something like this:

    if UIScreen.main.phoneSizeInInches() < 5.5 {
      //do something on all iPhones smaller than the plus
    }
    

    The default: tries to uses the screen size and scale to try and calculate the diagonal inches. This is in case some new device size appears, it will try its best to determine and code, such as the last example, should still work.

提交回复
热议问题