在 macOS 应用程序中,我设置了
NSWindow.backgroundColor = .clear
。这是一个错误,还是我做错了什么?
你知道解决方法吗?
环境:
macOS 12.5.1
Xcode 14.0
提前谢谢您。
import SwiftUI
@main
struct MacosPlaygroundApp: App {
var body: some Scene {
WindowGroup("Playground") {
ContentView()
.frame(width: 120, height: 300, alignment: .center)
}
}
}
struct ContentView: View {
private let items: [Item] = [
Item(id: "first", name: "First", sfSymbol: "house"),
Item(id: "second", name: "Second", sfSymbol: "sun.max"),
Item(id: "third", name: "Third", sfSymbol: "cloud"),
Item(id: "fourth", name: "Fourth", sfSymbol: "trash"),
Item(id: "fifth", name: "Fifth", sfSymbol: "scribble"),
]
var body: some View {
ScrollView {
LazyVGrid(columns: [gridItem], alignment: .center, spacing: 10) {
ForEach(items, id: \.id) { item in
itemView(item: item)
}
}
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
if let mainWindow = NSApplication.shared.windows.first(where: { $0.title == "Playground" }) {
mainWindow.backgroundColor = .clear
}
}
}
@ViewBuilder
private func itemView(item: Item) -> some View {
VStack(alignment: .center, spacing: 10) {
Image(systemName: item.sfSymbol)
Text(item.name)
}
.padding()
.background(.pink.opacity(0.5))
.cornerRadius(10)
}
private var gridItem: GridItem {
GridItem(
.adaptive(minimum: 100, maximum: 100),
spacing: 10,
alignment: .top
)
}
private struct Item {
let id: String
let name: String
let sfSymbol: String
}
}
我找到了解决方法:
.backgroundColor = .white.withAlphaComponent(0.000001)
,而不是.clear
。
窗口仍然显示透明(足够),并且我看不到渲染错误发生。
NSWindow.hasShadow = false
这应该有效。