binding - 为什么我的 SwiftUI 列表没有更新?

标签 binding swiftui

我使用 SwiftUI 列表并通过绑定(bind)将字符串传递到不同的 View 。 但是当我回去时列表没有更新。

这是我的例子:

struct ContentView: View {
    @State private var list = ["a", "b", "c"]
    @State private var item: String?
    @State private var showSheet = false
    
    
    var body: some View {
        List {
            ForEach(list.indices) { i in
                Button(action: {
                    item = list[i]
                    showSheet.toggle()
                }) {
                    Text(list[i])
                }
                
                
            }
        }
        .sheet(isPresented: $showSheet, content: {
            DetailView(input: $item)
        })
    }
}

以及详细信息页面:

struct DetailView: View {
    @Binding var input: String?
    
    var body: some View {
        Text(input ?? "")
        .onDisappear{
            print("changed to changed")
            input = "changed"
        }
    }
}

我想要实现的是,在我单击的每个项目上,我都会看到详细信息页面。之后该元素应更改为“已更改”。但这并没有发生。为什么?

最佳答案

您更新了 item 但未更新 list,因此看不到任何结果。这是更正的变体 - 存储选定的索引并按索引将绑定(bind)传递到列表。

使用 Xcode 12.1/iOS 14.1 进行测试

struct ContentView: View {
    @State private var list = ["a", "b", "c"]
    @State private var item: Int?
    
    
    var body: some View {
        List {
            ForEach(list.indices) { i in
                Button(action: {
                    item = i
                }) {
                    Text(list[i])
                }
            }
        }
        .sheet(item: $item, content: { i in
                DetailView(input: $list[i])
        })
    }
}

extension Int: Identifiable {
    public var id: Self { self }
}

struct DetailView: View {
    @Binding var input: String
    
    var body: some View {
        Text(input)
        .onDisappear{
            print("changed to changed")
            input = "changed"
        }
    }
}

关于binding - 为什么我的 SwiftUI 列表没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64664470/

相关文章:

c# - 如何绑定(bind)到文本框的 CaretIndex aka 光标位置

ScalaFX。实时绑定(bind)

variables - 如何通过文字进行模式匹配并同时为其分配变量?

mysql - 绑定(bind)Mysql 4.12

swift - SWIFTUI 中的 ASWebAuthenticationSession

ios - SwiftUI:动画文本颜色 - foregroundColor()

c# - 在资源中绑定(bind)数据上下文

SwiftUI:如何从 OutlineGroup 获取选择?

SwiftUI:支持多种模式

ios - SwiftUI 中的惰性属性