我正在迁移我的 iOS 应用程序以支持 MacCatalyst,但我想防止用户调整窗口大小。
你有什么建议吗?
从 Xcode11 Beta 5 开始,UIWindowScene
该类开始支持该属性sizeRestrictions
。
如果将sizeRestrictions.maximumSize
和设置sizeRestrictions.minimumSize
为相同的值,则窗口将无法调整大小。为此,只需在您的application:didFinishLaunchingWithOptions
方法中调用它(如果您使用的是UIKit):
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.forEach { windowScene in
windowScene.sizeRestrictions?.minimumSize = CGSize(width: 480, height: 640)
windowScene.sizeRestrictions?.maximumSize = CGSize(width: 480, height: 640)
}
如果您使用的是SwiftUI而不是 UIKit,您实际上应该将它添加到scene(_:willConnectTo:options:)
您的场景委托中。
注意:需要在 OSX 10.15 Beta 5 或更高版本中运行,否则会崩溃
在 SwiftUI 应用程序生命周期中,这对我有用:
import SwiftUI
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var userSettings = UserSettings()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(userSettings)
.environmentObject(KeyboardManager())
.onOpenURL(perform: { url in
let verificationCode = url.lastPathComponent
log.info(" Verification Code: \(verificationCode)")
userSettings.verificationCode = verificationCode
})
.onReceive(NotificationCenter.default.publisher(for: UIScene.willConnectNotification)) { _ in
#if targetEnvironment(macCatalyst)
// prevent window in macOS from being resized down
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.forEach { windowScene in
windowScene.sizeRestrictions?.minimumSize = CGSize(width: 800, height: 1000)
}
#endif
}
}
}
}
在文件 SceneDelegate.swift 中,添加以下内容:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.forEach { windowScene in
windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1268, height: 880)
windowScene.sizeRestrictions?.maximumSize = windowScene.sizeRestrictions!.minimumSize
}
guard let _ = (scene as? UIWindowScene) else { return }
}