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 -
他のアドベントカレンダー記事