英文:
My have a button with a popover that works fine on preview. When testing it on IOS device, can only click the button once then it is stuck
问题
我目前正在学习Swift,想要创建一个带有弹出视图的按钮来显示一些信息。在内容预览中,它运行得很好,但是当下载到我的iPhone后,如果我点击按钮一次,它就会工作。之后,按钮就坏了,弹出视图不显示。就像一个失效的按钮。
var body: some View {
@State var showHelp = false
NavigationView {
List {
//逻辑处理
}
.toolbar {
Button("帮助") {
showHelp = true
}
.popover(isPresented: $showHelp) {
Text("Foobar")
}
}
}
英文:
I am currently learning swift and want to create a button with a popover view to display some info. On the content preivew, it works just fine but when downloading to my iPhone, if I click the button once it works. After that, the button is broken and popover doesn't show. Almost like a dead button
var body: some View {
@State var showHelp = false
NavigationView {
List {
//logic stuff
}
.toolbar {
Button("Help") {
showHelp = true
}
.popover(isPresented: $showHelp) {
Text("Foobar")
}
}
}
答案1
得分: 1
尝试这种方法,将@State var showHelp = false
移出body
。以下是一个可运行的示例代码:
struct ContentView: View {
@State var showHelp = false // <-- 这里
var body: some View {
NavigationView {
List {
// 逻辑内容
Text("列表项")
}
.toolbar {
Button("帮助") {
showHelp = true
}
}
}
.popover(isPresented: $showHelp) { // <-- 这里
Text("Foobar")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
请注意,NavigationView
已被弃用,改用NavigationStack
。
英文:
try this approach, moving @State var showHelp = false
outside the body
. Here is a working example code:
struct ContentView: View {
@State var showHelp = false // <-- here
var body: some View {
NavigationView {
List {
//logic stuff
Text("the list")
}
.toolbar {
Button("Help") {
showHelp = true
}
}
}
.popover(isPresented: $showHelp) { // <-- here
Text("Foobar")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
See also: https://developer.apple.com/documentation/swiftui/state and https://developer.apple.com/documentation/swiftui/managing-user-interface-state
Note, NavigationView
is deprecated, use NavigationStack
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论