如何从NSWindow中访问SwiftUI Catalyst应用程序的属性?例如,通过通过NSWindow.moveableByWindowBackground拖动其背景来允许移动窗口。
我已经在SceneDelegate.swift中指定了基础知识。
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let app = UIApplication.shared
let delegate = app.delegate as! AppDelegate
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
#if targetEnvironment(macCatalyst)
if let titlebar = windowScene.titlebar {
titlebar.titleVisibility = .hidden
titlebar.toolbar = nil
}
if let sizeRestrictions = windowScene.sizeRestrictions {
sizeRestrictions.minimumSize = CGSize(width: 1300, height: 800)
}
window.canResizeToFitContent = true
#endif
window.rootViewController = UIHostingController(rootView: GreatHallView(screenerVM: delegate.screenerVM).environmentObject(SortingHat()))
self.window = window
window.makeKeyAndVisible()
}
}
首先,您需要Mhd Hejazi的动态 library。可以使用SPM将其包含在您的代码中。
接下来,是UIWindow的扩展:
extension UIWindow {
var nsWindow: NSObject? {
Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self)
}
}
现在您可以将NSWindow与UIWindow关联并调用方法并按如下所示提取属性:
#if targetEnvironment(macCatalyst)
let ns = window.nsWindow
let frame = ns?.value(forKey: "frame")
let size = (frame as! CGRect).size
ns!.setValue(CGSize(1.0, size.height/size.width), forKey: "aspectRatio")
print(Dynamic(ns!).isMovableByWindowBackground.asBool!)
Dynamic(ns!).setMovableByWindowBackground(true)
print(Dynamic(ns!).isMovableByWindowBackground.asBool!)
#endif
记住需要导入动态