SwiftUI MacCatalyst 的 isMovableByWindowBackground

isMovableByWindowBackground for SwiftUI MacCatalyst

如何从 NSWindow 访问 SwiftUI Catalyst 应用程序的属性?例如,允许通过 NSWindow.moveableByWindowBackground.

拖动其背景来移动 window

我指定的基础知识已经在 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 的 Dynamic 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 = Dynamic(ns!).frame.asCGRect!
    let size = frame.size
    Dynamic(ns!).setAspectRatio(CGSize(1.0, size.height/size.width))
    print(Dynamic(ns!).isMovableByWindowBackground.asBool!)
    Dynamic(ns!).setMovableByWindowBackground(true)
    print(Dynamic(ns!).isMovableByWindowBackground.asBool!)
    #endif

记得需要导入动态。此外,使用 Object-C 方法和属性,而不是 Swift。