刷新NavigationView环境对象

时间:2019-08-30 15:53:28

标签: swiftui swiftui-list

我试图创建一个可编辑的环境对象并将其放在列表中。 例如,仅当我切换选项卡时,变量才会刷新(因此,每当我离开NavigationView时,然后返回)。

以前,对ModalView也是如此。也许是错误吗?还是我做错了什么?

import SwiftUI
import Combine

struct TestView: View {

    @State var showSheet: Bool = false
    @EnvironmentObject var feed: TestObject
    func addObjects() {
        var strings = ["one","two","three","four","five","six"]
        for s in strings {
            var testItem = TestItem(text: s)
            self.feed.items.append(testItem)
        }
    }

    var body: some View {
        TabView {
            NavigationView {
                List(feed.items.indices, id:\.self) { i in
                    NavigationLink(destination: detailView(feed: self._feed, i: i)) {
                        HStack {
                            Text(self.feed.items[i].text)
                            Text("(\(self.feed.items[i].read.description))")
                        }
                    }
                }
            }
                .tabItem({ Text("Test") })
                .tag(0)

            Text("Blank")
                .tabItem({ Text("Test") })
                .tag(0)
        }.onAppear {
            self.addObjects()
        }
    }
}

struct detailView: View {
    @EnvironmentObject var feed: TestObject
    var i: Int
    var body: some View {
        VStack {
            Text(feed.items[i].text)
            Text(feed.items[i].read.description)
            Button(action: {  self.feed.items[self.i].isRead.toggle() }) {
                Text("Toggle read")
            }
        }
    }
}

final class TestItem: ObservableObject {
    init(text: String) {
        self.text = text
        self.isRead = false
    }
    static func == (lhs: TestItem, rhs: TestItem) -> Bool {
        lhs.text < rhs.text
    }
    var text: String
    var isRead: Bool

    let willChange = PassthroughSubject<TestItem, Never>()
    var read: Bool {
        set {
            self.isRead = newValue
        }
        get {
            self.isRead
        }
    }
}

class TestObject: ObservableObject {
    var willChange = PassthroughSubject<TestObject, Never>()

    @Published var items: [TestItem] = [] {
        didSet {
            willChange.send(self)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

  1. 您必须使用willSet而不是didSet。
  2. TestItem应该是一个值类型:struct或enum。 SwiftUI的观察系统仅适用于值类型。

答案 1 :(得分:0)

尝试在目的地传递 .environmentObject:

NavigationLink(destination: detailView(feed: self._feed, i: i).environmentObject(x))