Swiftui: How to Close one Tab in a TabView?

Viewed 35

I'm learning SwiftUI and having trouble with closing Each Tab View Element.

My App shows photos from user's album by TabView with pageViewStyle one by one.

And What I want to make is user can click save button in each view, and when button is clicked, save that photo and close only that view while other photos are still displayed. So unless all photos are saved or discarded, if user clicks save button, TabView should automatically move to another one.

However, I don't know how to close only one Tab Element. I've tried to use dismiss() and dynamically changing vm.images element. Latter one actually works, but it displays awkward movement and it also requires quite messy code. How could I solve this issue?

Here is my code.

TabView {
    ForEach(vm.images, id: \.self) { image in
        TestView(image: image)
    }
}
.tabViewStyle(.page(indexDisplayMode: .never))
struct TestView: View {
    @ObservedObject var vm: TestviewModel
    ...

    var body: some View {
        VStack(spacing: 10) {
            Image(...)
            
            Spacer()
            
            Button {
               ...
            } label: {
                Text("Save")
            }

        }
2 Answers

You need actually to remove saved image from the viewModel container, and UI will be updated automatically

literally

Button {
   vm.images.removeAll { $0.id == image.id }   // << here !!
} label: {
    Text("Save")
}

You need to use the selection initializer of TabView in order to control what it displays. So replace TabView with:

TabView(selection: $selection)

Than add a new property: @State var selection: YourIdType = someDefaultValue, and in the Button action you set selection to whatever you want to display.

Also add .tag(TheIdTheViewWillUse) remember that whatever Id you use must be the same as your selection variable. I recommend you use Int for the simple use.

Related