nachonavarro / Pages

📖 A lightweight, paging view solution for SwiftUI
MIT License
586 stars 55 forks source link

Feature: Dynamically removing a page #7

Closed NeverwinterMoon closed 4 years ago

NeverwinterMoon commented 4 years ago

I would be very interested in being able to dynamically remove a page by, say, clicking on a button on said page. Currently, this is not supported and if the data element is removed, PageViewController crashes with index out of range.

nachonavarro commented 4 years ago

That's a great idea, another issue mentions adding pages as well. I'll take a look, but feel free to take a look as well and submit a pull request!

nachonavarro commented 4 years ago

This is fixed in the new version. For instance:

import SwiftUI
import Pages

struct Car {
    var model: String
}

struct ContentView: View {
    @State var cars = [Car(model: "Ford"), Car(model: "Ferrari")]
    @State var index = 0

    var body: some View {
        ModelPages(cars, currentPage: $index) { i, car in
            Button(action: {
                self.cars.remove(at: 1)
            }, label: {
                Text("Remove car!")
            })
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Some care must be taken if you're removing the element in the array and you're currently displaying that element as a page. In this case you could do something like:

struct ContentView: View {
    @State var cars = [Car(model: "Ford"), Car(model: "Ferrari")]
    @State var index = 0

    var body: some View {
        ModelPages(cars, currentPage: $index) { i, car in
            Button(action: {
                self.cars.remove(at: 1)
                self.index = 0
            }, label: {
                Text("Remove car!")
            })
        }
    }
}