问题
I am sure there is a better, more proper way to do this. But right now I am using UIScreen.main.bounds to detect if I am dealing with an iPhone X (812 tall) or not. This specific app is landscape only, btw. So this is what I have in this function where I am crating slides for a slide view:
func setupSlideViews(slideView: [SlideView]) {
let screenSize = UIScreen.main.bounds
var frame: CGRect!
if screenSize.width == 812 {
frame = scrollView.frame
} else {
frame = view.frame
}
scrollView.frame = frame
scrollView.contentSize = CGSize(width: frame.width * CGFloat(slideViews.count), height: frame.height)
for (i, slideView) in slideViews.enumerated() {
slideView.frame = CGRect(x: frame.width * CGFloat(i), y: 0, width: frame.width, height: frame.height)
scrollView.addSubview(slideView)
}
}
But how do you check for the model?
回答1:
If you need to detect if a device is iPhoneX don't use bounds
, it depends on the orientation of the device. So if the user opens your app in portrait mode it will fail. You can use Device property nativeBounds
which doesn't change on rotation.
In iOS 8 and later, a screen’s bounds property takes the interface orientation of the screen into account. This behavior means that the bounds for a device in a portrait orientation may not be the same as the bounds for the device in a landscape orientation. Apps that rely on the screen dimensions can use the object in the fixedCoordinateSpace property as a fixed point of reference for any calculations they must make. (Prior to iOS 8, a screen’s bounds rectangle always reflected the screen dimensions relative to a portrait-up orientation. Rotating the device to a landscape or upside-down orientation did not change the bounds.)
extension UIDevice {
var iPhoneX: Bool {
return UIScreen.main.nativeBounds.height == 2436
}
}
usage
if UIDevice.current.iPhoneX {
print("This device is a iPhoneX")
}
来源:https://stackoverflow.com/questions/46535473/how-can-i-detect-if-my-device-is-an-iphonex-in-swift-4