Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Last active May 6, 2021 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zntfdr/f9e34a072c84f52b6ec65c4350299ffe to your computer and use it in GitHub Desktop.
Save zntfdr/f9e34a072c84f52b6ec65c4350299ffe to your computer and use it in GitHub Desktop.
// "Fix" for Xcode 12.5 SwiftUI navigation issue.
import SwiftUI
enum ContentViewNavigation: Identifiable {
case one
case two(number: Int)
case three(text: String)
// MARK: Identifiable
var id: Int {
switch self {
case .one:
return 1
case .two:
return 2
case .three:
return 3
}
}
}
struct ContentView: View {
@State private var showingNavigation: ContentViewNavigation?
var body: some View {
NavigationView {
VStack {
Button("Go to navigation one") {
showingNavigation = .one
}
Button("Go to navigation two") {
showingNavigation = .two(number: Int.random(in: 1...5))
}
Button("Go to navigation three") {
showingNavigation = .three(text: ["five", "stars"].randomElement()!)
}
}
.navigation(item: $showingNavigation, destination: presentNavigation)
}
}
@ViewBuilder
func presentNavigation(_ navigation: ContentViewNavigation) -> some View {
switch navigation {
case .one:
Text(verbatim: "one")
case .two(let number):
Text("two \(number)")
case .three(let text):
Text("three \(text)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension NavigationLink where Label == EmptyView, Destination == AnyView {
public init<V: Identifiable, Destination2: View>(
item: Binding<V?>,
destination: @escaping (V) -> Destination2
) {
let value: V? = item.wrappedValue
let isActive: Binding<Bool> = Binding(
get: { item.wrappedValue != nil },
set: { value in
if !value {
item.wrappedValue = nil
}
}
)
self.init(
destination:
AnyView(Group {
if let value = value {
destination(value)
} else {
EmptyView()
}
}),
isActive: isActive,
label: EmptyView.init
)
}
}
extension View {
func navigation<V: Identifiable, Destination: View>(
item: Binding<V?>,
destination: @escaping (V) -> Destination
) -> some View {
background(NavigationLink<EmptyView, AnyView>(item: item, destination: destination))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment