如何解决SwiftUI:更改其标签后,ToolbarItem位置:.principal中的按钮不起作用 Xcode 12 beta 6 代码:
Xcode 12 beta 6
工具栏中有一个按钮,其标签文本绑定到状态var buttonTitle
。我想点击此按钮以触发图纸视图,选择以更改绑定变量。
返回到内容视图后,按钮的标题将更新。但是,如果再次点击该按钮,它将无法正常工作。
代码:
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)
}
}
}
,
像这样将sheet(...)
移动到ToolbarItem范围之外:
NavigationView {
..
}.sheet(...)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。