简体   繁体   中英

SwiftUI hide list item from list item view

So, let's say I have a SwiftUI List and Toggle (heavily simplified):

List {

    Toggle(isOn: $isOn) {

        Text("Toggle")

    }

    ForEach(arr) { item in

        if isOn || !item.isComplete {

            Row(item: item)
        }

    }

}

Then my Row:

HStack {

    Button(action: {

        self.item.isComplete.toggle() // isComplete is a Boolean value

    }) {

        Text("Button")

    }

    Text(item.isComplete ? "Complete" : "Not complete")

}

The toggle should change the list, swapping between all items, and only non-completed items. This works perfectly. However, I want this to function so that when I press the button, the list is updated instantly and it goes away, rather than me having to re-switch the toggle. How can this be done?

Note that Lists are still buggy when it comes to large sets of data. Here you have an example that does what you asked. I am passing the ObservableObject, but you can also put it in the environment. That's up to you.

import SwiftUI

struct Item: Identifiable {
    let id = UUID()
    var isComplete: Bool = false
}

class Model: ObservableObject {
    @Published var isOn: Bool = false
    @Published var arr = [Item(isComplete: true), Item(isComplete: false), Item(isComplete: true), Item(isComplete: false), Item(isComplete: true), Item(isComplete: true)]
}

struct ContentView: View {
    @ObservedObject var model = Model()

    var body: some View {
        List {

            Toggle(isOn: $model.isOn) { Text("Toggle") }

            ForEach(self.model.arr.filter { model.isOn ? true : $0.isComplete }) { item in
                Row(item: item, model: self.model)
            }
        }
    }
}

struct Row: View {
    let item: Item
    @ObservedObject var model: Model

    var body: some View {
        HStack {

            Button(action: {

                if let idx = self.model.arr.firstIndex(where: { $0.id == self.item.id }) {
                    self.model.arr[idx].isComplete.toggle()
                    self.model.isOn = false
                }

            }) {

                Text("Button")

            }

            Text(item.isComplete ? "Complete" : "Not complete")

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM