跟踪已发布项目列表的状态变量

时间:2019-12-25 14:23:00

标签: swiftui

我正在学习SwiftUI并遇到数据流问题。 我不知道如何创建“状态”变量来跟踪已发布子项的列表。

如果至少选择了一个子项,我需要一个true的变量。这些项映射到有效的SwiftUI拨动开关。 (不允许计算属性)

属性包装器无法应用于计算出的属性

class Main : ObservableObject {
    @Published var items : [Item]

    //This is what i want, but not allowed
    @Published var selectedItemsExist : Bool {
        get {
            var exists = false
            for item in items {
                if item.selected {
                    exists = true
                    break
                }
            }
            return exists
        }
    }

    init(items: [Item]) {
        self.items = items
    }
}

class Item : Identifiable, ObservableObject {
    var id = UUID()
    var name : String!
    @Published var selected : Bool = false
}

然后我认为可以做类似的事情

if main.selectedItemsExist {
    Text("This text is shown if at least on toggle is on")
}

任何指导表示赞赏!

1 个答案:

答案 0 :(得分:1)

请在下面的方法演示中找到如何实现的方法。经测试可与Xcode 11.2 / iOS 13.2一起使用

class Main : ObservableObject {

    @Published var items : [Item] {
        didSet { // << as item is value array will be updated on item changed
            var exists = false
            for item in items {
                if item.selected {
                    exists = true
                    break
                }
            }
            self.selectedItemsExist = exists
        }
    }

    @Published var selectedItemsExist : Bool = false

    init(items: [Item]) {
        self.items = items
    }
}


struct Item : Identifiable { // << value type, so changed on any property change
    var id = UUID()
    var name : String!
    var selected : Bool = false
    init(_ name: String) {
        self.name = name
    }
}

struct TestCalculablePublishing: View {
    @ObservedObject var main = Main(items: [Item("1"), Item("2"), Item("3")])

    var body: some View {
        VStack {
            Button("Test") {
                self.main.items[1].selected.toggle() // << just for test purpose
            }
            if main.selectedItemsExist {
                Text("This text is shown if at least on toggle is on")
            }
        }
    }
}

struct TestCalculablePublishing_Previews: PreviewProvider {
    static var previews: some View {
        TestCalculablePublishing()
    }
}