如何在Swift 4中检测iPhone 7 Plus/X屏幕尺寸及OC代码转Swift 4?
Hey there! Let's walk through your two Swift 4 questions in detail—first detecting iPhone 7 Plus and iPhone X screen sizes, then converting your Objective-C code over.
To reliably identify these specific models, we'll use the nativeBounds property of UIScreen (this gives physical pixel dimensions, which are consistent for each device model, unlike point-based sizes that vary with scale factors).
- iPhone 7 Plus has a native screen height of 1920 pixels
- iPhone X has a native screen height of 2436 pixels
First, we'll confirm the device is an iPhone (not an iPad or other device) using UIDevice.current.userInterfaceIdiom, then check the native height. Here's the code:
import UIKit func isIPhone7Plus() -> Bool { return UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.size.height == 1920 } func isIPhoneX() -> Bool { return UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.size.height == 2436 } // Example usage if isIPhoneX() { print("This is an iPhone X") } else if isIPhone7Plus() { print("This is an iPhone 7 Plus") }
Your original Objective-C code checks for an iPhone X-sized screen, then initializes a YSLContainerViewController with child controllers, a top bar height, parent view controller, and delegate. Here's the clean Swift 4 equivalent:
import UIKit // Assume controller1 through controller7 are already initialized UIViewController instances if UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.size.height == 2436 { let containerVC = YSLContainerViewController( controllers: [controller1, controller2, controller3, controller4, controller5, controller6, controller7], topBarHeight: 276, parentViewController: self ) containerVC.delegate = self // Replace with your delegate object if it's not `self` // Don't forget to add the container to your view hierarchy (example below) self.addChild(containerVC) view.addSubview(containerVC.view) containerVC.didMove(toParent: self) }
Key conversion notes:
[UIDevice currentDevice]becomesUIDevice.currentin SwiftUIUserInterfaceIdiomPhonesimplifies to.phoneUIScreen.mainScreenis nowUIScreen.main- Objective-C array literals
@[...]become Swift's[...] - The alloc/init pattern
[[YSLContainerViewController alloc] initWithControllers:...is replaced with a direct initializer call - Ensure your class conforms to the
YSLContainerViewControllerDelegateprotocol if settingdelegate = self(you'll need to implement any required methods)
内容的提问来源于stack exchange,提问作者Appu Y

