Xcode 12 beta 6
工具栏中有一个按钮,其标签文本绑定(bind)到状态变量buttonTitle
。我想点击这个按钮来触发工作 TableView ,选择更改绑定(bind)变量。
返回内容 View 后,按钮的标题将更新。但如果再次点击该按钮,则不起作用。
代码:
struct ContentView: View {
@State var show = false
@State var buttonTitle = "button A"
var body: some View {
NavigationView {
Text("Hello World!")
.toolbar {
ToolbarItem(placement: .principal) {
Button {
show.toggle()
} label: {
Text(buttonTitle)
}
.sheet(isPresented: $show) {
SelectTitle(buttonTitle: $buttonTitle)
}
}
}
}
}
}
struct SelectTitle: View {
@Environment(\.presentationMode) var presentationMode
@Binding var buttonTitle: String
var body: some View {
Button("Button B") {
buttonTitle = "Button B"
presentationMode.wrappedValue.dismiss()
}
}
}
最佳答案
这是已知的工具栏工作表布局问题,另请参阅here 。您可以向 Apple 提交另一个反馈。
这是针对您的情况的解决方法 - 使用回调在工作表关闭后更新工具栏项目。使用 Xcode 12b5 进行测试。
struct ContentView: View {
@State var show = false
@State var buttonTitle = "button A"
var body: some View {
NavigationView {
Text("Hello World!")
.toolbar {
ToolbarItem(placement: .principal) {
Button {
show.toggle()
} label: {
Text(buttonTitle)
}
.sheet(isPresented: $show) {
SelectTitle(buttonTitle: buttonTitle) {
self.buttonTitle = $0
}
}
}
}
}
}
}
struct SelectTitle: View {
@Environment(\.presentationMode) var presentationMode
@State private var buttonTitle: String
let callback: (String) -> ()
init(buttonTitle: String, callback: @escaping (String) -> ()) {
_buttonTitle = State(initialValue: buttonTitle)
self.callback = callback
}
var body: some View {
Button("Button B") {
buttonTitle = "Button B"
presentationMode.wrappedValue.dismiss()
}
.onDisappear {
callback(buttonTitle)
}
}
}
关于SwiftUI:ToolbarItem(放置:.principal)中的按钮在更改标签后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63607324/