【问题标题】:SwiftUI @State is updated only once when put inside NavigationView (macOS app)SwiftUI @State 在放入 NavigationView(macOS 应用程序)时仅更新一次
【发布时间】:2020-09-14 04:43:32
【问题描述】:

问题

我在 NavigationView 中放置了一个增加计数器的简单按钮,但应用程序似乎只更新了一次 @State 值;稍后的点击被忽略。在 NavigationLink 之间切换会导致视图更新,但是为什么在 counter 发生更改后它不会自动更新?

事实

otherView 在我将其放在导航视图之外后可以正常工作。

代码

import SwiftUI

struct ContentView: View {
    
    @State var counter = 0
    
    var otherView: some View {
        Button(action: {
            counter += 1
        }, label: {
            Text(String(counter))
        }).frame(maxWidth: .infinity, maxHeight: .infinity).padding()
    }
    
    var body: some View {
        HStack {
            NavigationView {
                List {
                    NavigationLink("otherview", destination: otherView)
                }.listStyle(SidebarListStyle())
            }
        }.frame(minWidth: 500, minHeight: 400)
    }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    尝试将otherView 移动到单独的 SwiftUI 视图中,如下所示:

    struct ButtonView: View {
        
        @State var counter = 0
        
        var body: some View {
            Button(action: {
                counter += 1
            }, label: {
                Text(String(counter))
            }).frame(maxWidth: .infinity, maxHeight: .infinity).padding()
        }
        
    }
    

    然后在你的ContentView 中这样称呼它:

    struct ContentView: View {
           
        var body: some View {
            HStack {
                NavigationView {
                    List {
                        NavigationLink("otherview", destination: ButtonView())
                    }.listStyle(SidebarListStyle())
                }
            }.frame(minWidth: 500, minHeight: 400)
        }
    }
    

    【讨论】:

    • 工作,但在我将ButtonView 中的@Binding 替换为@State 之后。谢谢!
    猜你喜欢
    • 2020-04-10
    • 2019-10-30
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多