Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of the UISplitViewController in SwiftUI

Tags:

ios

swift

swiftui

I need to implement an UI which close to the default Mail app in iPad and iPhone.

The App has two sections, typically, the master view will be displayed on the left side and detail view will be displayed in the right side in iPad.

In the phone, the master view will be displayed on whole screen, the detail view can be pushed as second screen.

How to implement it in the new SwiftUI

like image 410
Qing Xu Avatar asked Nov 28 '22 13:11

Qing Xu


1 Answers

There is not really a SplitView in SwiftUI, but what you describe is automatically accomplished when you use the following code:

import SwiftUI

struct MyView: View {
    var body: some View {
        NavigationView {
            // The first View inside the NavigationView is the Master
            List(1 ... 5, id: \.self) { x in
                NavigationLink(destination: SecondView(detail: x)) {
                    Text("Master\nYou can display a list for example")
                }
            }
            .navigationBarTitle("Master")
            // The second View is the Detail
            Text("Detail placeholder\nHere you could display something when nothing from the list is selected")
                .navigationBarTitle("Detail")
        }
    }
}

struct SecondView: View {
    var detail: Int
    var body: some View {
        Text("Now you are seeing the real detail View! This is detail \(detail)")
    }
}

This is also why the .navigationBarTitle() modifier should be applied on the view inside the NavigationView, instead of on the NavigationView itself.

Bonus: if you don't like the splitView navigationViewStyle, you can apply the .navigationViewStyle(StackNavigationViewStyle()) modifier on the NavigationView.

Edit: I discovered that the NavigationLink has an isDetailLink(Bool) modifier. The default value appears to be true, because by default the "destination" is presented in the detail view (on the right). But when you set this modifier to false, the destination is presented as a master (on the left).

like image 53
cbjeukendrup Avatar answered Dec 09 '22 19:12

cbjeukendrup