使用xcode 12.3和swift 5.3结合SwiftUI App生命周期构建macOS应用程序,访问和更改NSWindow外观和行为的最佳方法是什么
编辑:,我真正想要的是NSWindow实例。
我添加了一个AppDelegate,但据我所知,NSWindow很可能是nil,因此无法修改,只需在这里创建一个类似于AppKit App Delegate生命周期方法的窗口,就会在启动时出现两个窗口。
一种解决方案是防止默认窗口出现,并将其全部留给applicationDidFinishLaunching方法处理,但不确定这是否可行或合理。
WindowStyle协议看起来是一种可能的解决方案,但不确定在这个阶段如何最好地利用CustomWindowStyle,以及它是否为细粒度控制提供了对NSWindow实例的访问。
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// In AppKit simply create the NSWindow and modify style.
// In SwiftUI creating an NSWindow and styling results in 2 windows,
// one styled and the other default.
}
}
@main
struct testApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate : AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}发布于 2020-12-21 23:55:36
虽然我不能完全确定这是正确的方法,基于这个问题的答案:https://stackoverflow.com/a/63439982/792406,我已经能够访问NSWindow实例并修改它的外观。
作为快速参考,下面是一个基于Asperi提供的使用xcode 12.3、swift 5.3和SwiftUI应用程序生命周期的原始代码的工作示例。
@main
struct testApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class Store {
var window: NSWindow
init(window: NSWindow) {
self.window = window
self.window.isOpaque = false
self.window.backgroundColor = NSColor.clear
}
}
struct ContentView: View {
@State private var window: NSWindow?
var body: some View {
VStack {
Text("Loading...")
if nil != window {
MainView(store: Store(window: window!))
}
}.background(WindowAccessor(window: $window))
}
}
struct MainView: View {
let store: Store
var body: some View {
VStack {
Text("MainView with Window: \(store.window)")
}.frame(width: 400, height: 400)
}
}
struct WindowAccessor: NSViewRepresentable {
@Binding var window: NSWindow?
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
self.window = view.window
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}发布于 2020-12-22 17:24:18
有趣的方法@hillmark。
我还让它使用了一种使用NSApplicationDelegateAdaptor的方法。
我相信下面的代码只会帮助您处理一个窗口MacOS SwiftUI应用程序--一个多窗口应用程序可能需要处理所有的窗口,而不仅仅是第一个窗口。
我也不确定对我的方法是否有任何警告。
现在,这正好解决了我的问题,但我也将检查您的方法。
import SwiftUI
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
if let window = NSApplication.shared.windows.first {
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.isOpaque = false
window.backgroundColor = NSColor.clear
}
}
}
@main
struct AlreadyMacOSApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
NewLayoutTest()
}
}
}https://stackoverflow.com/questions/65379307
复制相似问题