【发布时间】:2021-08-04 22:59:40
【问题描述】:
在 Apple 的日历应用程序中,它们提供了一个工具栏项,可以根据某些状态切换其样式。它本质上是一个切换。我正在尝试在 SwiftUI 中重新创建相同的东西,并使其在明暗模式下都能正常工作。我能够制作一个按预期工作的视图,直到我将它放入工具栏中并且它不再显示选定状态。这是我的尝试:
struct ToggleButtonView: View {
@State private var isOn = false
var body: some View {
Button(action: {
isOn.toggle()
}, label: {
if isOn {
Image(systemName: "list.bullet.below.rectangle")
.accentColor(Color(.systemBackground))
.background(RoundedRectangle(cornerRadius: 5.0)
.fill(Color.accentColor)
.frame(width: 26, height: 26))
} else {
Image(systemName: "list.bullet.below.rectangle")
}
})
.accentColor(.red)
}
}
这是我实际将按钮放入工具栏的方式:
struct TestView: View {
var body: some View {
NavigationView {
ScrollView {
ForEach(0..<5) { number in
Text("Number \(number)")
}
}
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
ToggleButtonView()
Button(action: {}, label: {
Image(systemName: "plus")
})
}
}
.navigationTitle("Plz halp")
}
.accentColor(.red)
}
}
以下是日历应用的屏幕截图。请注意搜索图标左侧的工具栏项。
【问题讨论】:
-
你能把代码显示在哪里以及如何将它放入工具栏吗?
-
是的!帖子应该更新了。
-
在 macos 12.beta、xcode 13.beta、target ios 15 和 macCatalyst 上对我来说在明暗模式下都很好用。可能在旧系统上有所不同。
-
我没想到会这样。我在 macOS 11.4,Xcode 12.5.1,目标 iOS 14 上。我什至创建了一个新项目并完全复制了我在这篇文章中放置的内容,并且当切换打开时它不显示背景。
-
有人可以确认它适用于 macos 12.beta、xcode 13.beta、目标 ios 15。