以下代码是从在 MacOS 11 下编译和工作的应用程序中删除的。它显示了一个选项卡栏 - 单击一个项目将突出显示它。标签栏下方是一个文本编辑字段,您可以在其中编辑所选标签的标题。
有2个问题:
- 标题编辑器中显示的选项卡标题与所选选项卡不同相
- 无论选择了哪个选项卡项目,当编辑标题时,它总是更新第一个选项卡
我不确定我是否非常幸运,这段代码曾经在 Big Sur 下工作过,或者 Monterey 是否存在问题。我绝对不会把它作为示例代码 - 我确信有更好的方法来实现它,但就它是否应该工作征求意见。
import SwiftUI
class Document: ObservableObject {
var tabs = [Tab(id: 0), Tab(id: 1)]
@Published var activeTab: Int = 0
}
class Tab: ObservableObject, Identifiable {
let id: Int
@Published var title: String
init(id: Int) {
self.id = id
self.title = "Tab \(id)"
}
}
@main
struct Test: App {
@StateObject var document: Document = Document()
var body: some Scene {
WindowGroup {
ContentView()
.padding()
.environmentObject(document)
}
}
}
struct ContentView: View {
@EnvironmentObject var document: Document
var body: some View {
TabBar()
TabEditView(activeTab: document.tabs[document.activeTab])
}
}
struct TabEditView: View {
@EnvironmentObject var document: Document
@ObservedObject var activeTab: Tab
@State var title: String = ""
init(activeTab: Tab) {
print("CONSOLE - Init TabEditView for tab \(activeTab.id)")
self.activeTab = activeTab
}
var body: some View {
HStack {
Text("Tab title:")
TextField("Tab title:", text: $title, onCommit: { activeTab.title = title })
.onAppear { title = activeTab.title }
.onChange(of: document.activeTab) { _ in
print("CONSOLE - Updating TextField from tab \(activeTab.id)")
title = activeTab.title
}
}
}
}
struct TabBar: View {
@EnvironmentObject var document: Document
var body: some View {
HStack {
ForEach(document.tabs, content: TabItem.init)
}
}
}
struct TabItem: View {
@EnvironmentObject var document: Document
@ObservedObject var tab: Tab
init(_ tab : Tab) { self.tab = tab }
var body: some View {
Text(tab.title)
.padding(2)
.background(tab.id == document.activeTab ? .red : .clear)
.cornerRadius(4)
.onTapGesture {
document.activeTab = tab.id
}
}
}