是否有一种 Swifty 方法可以检测 macOS 上 SwiftUI 中窗口的背景颜色,无论当前主题如何(深色模式或浅色模式),该方法都可以可靠地工作?
例如,如果要制作一个与窗口背景“融合”的实心矩形,他们会使用哪种颜色?
这个答案建议使用NSColor.xxxBackgroundColor:
SwiftUI:获取动态背景颜色(深色模式或浅色模式)
然而,这对我来说不太管用。下面是一些测试代码(Xcode 12.5,Swift 5.4),它生成了三个不同NSColors 的矩形。我正在寻找一种与背景融为一体的。
struct TestView: View {
var body: some View {
VStack(spacing: 20) {
Text("This text is on the default background")
HStack(spacing: 30) {
Text("windowBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.windowBackgroundColor))
Text("underPageBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.underPageBackgroundColor))
Text("textBackgroundColor")
.frame(width: 200, height: 100)
.background(Color(NSColor.textBackgroundColor))
}
}
.padding(20)
}
}
Run Code Online (Sandbox Code Playgroud)
作为练习,我尝试在 macOS (Big Sur) 上复制 Safari 中的“高级”首选项窗格,如下所示(没有导航栏):
Safari 高级偏好设置的屏幕截图
我想知道正确的方法是水平和垂直地正确对齐窗口中的所有元素。我已经使用 a 进行了第一次尝试LazyVGrid,它非常接近,但我有几个问题:
LazyVGrid办法做到吗,或者有更好的办法吗?ForEach和AnyViews 。有什么更好的办法呢?这是代码:
struct PrefsAdvancedView: View {
let emptyCell = AnyView(Color(NSColor.clear))
@Binding var bool1: Bool
@Binding var bool2: Bool
@State private var selectedStrength = "9"
let strengths = [ "9" ]
@State private var selectedSheet = "None Selected"
let sheets = [ "None Selected", "fake1" ]
@State private var selectedEncoding = "Western (ISO …Run Code Online (Sandbox Code Playgroud) 给定一个带有 EditButton() 的列表视图,如果正在编辑该视图(用户点击“编辑”按钮),当用户离开该视图时,如何以编程方式禁用编辑模式?(例如,与 iPhone 上的“电话”应用程序中的“收藏夹”视图类似的行为)
struct ContentView2: View {
@State var fruits = ["Apple", "Banana"]
var body: some View {
NavigationView {
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
.onDelete { _ in
print("Delete")
}
}
.toolbar {
EditButton()
}
}
.onDisappear {
// make List's editMode be .inactive; how?
}
}
}
Run Code Online (Sandbox Code Playgroud)