14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIAdvent Calendar 2022

Day 19

[SwiftUI] まだ `NavigationLink(...) { EmptyView() }` で消耗してるの?

Last updated at Posted at 2022-12-19

Tl;Dr

+ EmptyLink(isActive: $isActive) {
+     ChildView()
+ }
- NavigationLink(isActive: $isActive, destination: { ChildView() }) {
-     EmptyView()
- }

How to use

struct ContentView: View {
    @State var isActive: Bool = false

    var body: some View {
        NavigationView {
            VStack {
                Button("画面遷移") { isActive = true }

                // 🎄 Readable 🎁
                EmptyLink(isActive: $isActive) {
                    ChildView()
                }

                // NavigationLink(isActive: $isActive, destination: { ChildView() }) {
                //     EmptyView()
                // }
            }
            .navigationTitle("18日目")
        }
    }
}

struct ChildView: View {
    var body: some View {
        Text("Child")
            .navigationTitle("Child")
    }
}

Source code

struct EmptyLink<Destination: View>: View {
    private var navigationLink: () -> NavigationLink<EmptyView, Destination>

    init(
        isActive: Binding<Bool>,
        @ViewBuilder destination: @escaping () -> Destination
    ) {
        navigationLink = {
            NavigationLink(
                destination: destination(),
                isActive: isActive,
                label: { EmptyView() }
            )
        }
    }

    init<V: Hashable>(
        tag: V,
        selection: Binding<V?>,
        @ViewBuilder destination: @escaping () -> Destination
    ) {
        navigationLink = {
            NavigationLink(
                tag: tag,
                selection: selection,
                destination: destination,
                label: { EmptyView() }
            )
        }
    }

    var body: some View {
        navigationLink()
    }
}

おわりに

SwiftUI Advent Calendar 2022 の19日目の記事でした 🎁

- Merry Christmas, SwiftUI Lovers -

他のアドベントカレンダー記事

14
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?