How to use `List` on different iOS devices

105 views Asked by At

I'm developing a SwiftUI application that should work on iPad and iPhone devices, but I have a problem with using List. I have attached photos for the expected behavior I need from the List.

I also have tried using NavigationSplitView but it does not select items in the list.

This is my code:

struct VehicleListView: View {
    @ObservedObject var viewModel: VehicleUserViewModel = VehicleUserViewModel()
    @State private var tappedVehicle: VehicleModel?
    
    var body: some View {
        NavigationSplitView {
            List(viewModel.vehicles, id: \.id) { vehicle in
                HStack {
                    VStack(alignment: .leading) {
                        Text(vehicle.brand ?? "")
                            .bold()
                            .foregroundStyle(.blue)
                        
                        Text(vehicle.plateId ?? "")
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .imageScale(.large)
                }
            }
            .navigationBarTitle("Araçlar")
        } detail: {
            if let vehicle = tappedVehicle {
                CustomVehicleView(fetchedVehicle: Binding(get: {
                    vehicle
                }, set: { newValue in
                    tappedVehicle = newValue
                }))
            } else {
                EmptyView()
            }
        }
    }
}

This is how the list is displayed on the Settings app on iPhone devices. When clicked on a list element, it navigates you to the page related to that element. (See image here)

This is how to use the list on the settings page on iPad devices. When a list element is clicked, the page related to that element opens right next to the page. (See image here)

How is this used? Does the SwiftUI code adjust this usage based on the type of device?

1

There are 1 answers

4
Pierre Janineh On

If you need support for iOS 16.0+, use NavigationSplitView, it does exactly what you're asking for:

@State private var vehicle: Vehicle? = nil

init() {
    self.vehicle = viewModel.vehicles[0]
}


var body: some View {
    NavigationSplitView {
        List(viewModel.vehicles,
             selection: $vehicle) { v in
            Text(v.brand)
        }
    } detail: {
        CustomVehicleView(fetchedVehicle: $vehicle)
    }
}

Ensure your Vehicle conforms to Identifiable or/and Hashable in order for you to be able to use List(_:selection:rowContent:):