That's because the navigation link is performed eagerly. I made a view to run the creation on tap.
import SwiftUI
struct LazyView<Content>: View where Content: View {
private let viewBuild: () -> Content
fileprivate init(_ viewBuild: @escaping () -> Content) {
self.viewBuild = viewBuild
}
init(_ viewBuild: @escaping @autoclosure () -> Content) {
self.init(viewBuild)
}
var body: some View {
viewBuild()
}
}
extension NavigationLink {
init<V>(lazyDestination: @escaping @autoclosure () -> V, @ViewBuilder label: () -> Label) where Destination == LazyView<V> {
self.init(destination: LazyView(lazyDestination), label: label)
}
init<V>(lazyDestination: @escaping @autoclosure () -> V, isActive: Binding<Bool>, @ViewBuilder label: () -> Label)
where Destination == LazyView<V> {
self.init(destination: LazyView(lazyDestination), isActive: isActive, label: label)
}
init<V, T>(lazyDestination: @escaping @autoclosure () -> V, tag: T, selection: Binding<T?>, @ViewBuilder label: () -> Label)
where T : Hashable, Destination == LazyView<V> {
self.init(destination: LazyView(lazyDestination), tag: tag, selection: selection, label: label)
}
}
extension NavigationLink where Label == Text {
init<V>(_ titleKey: LocalizedStringKey, lazyDestination: @escaping @autoclosure () -> V) where Destination == LazyView<V> {
self.init(titleKey, destination: LazyView(lazyDestination))
}
init<V, S>(_ title: S, lazyDestination: @escaping @autoclosure () -> V) where S : StringProtocol, Destination == LazyView<V> {
self.init(title, destination: LazyView(lazyDestination))
}
init<V>(_ titleKey: LocalizedStringKey, lazyDestination: @escaping @autoclosure () -> V, isActive: Binding<Bool>)
where Destination == LazyView<V> {
self.init(titleKey, destination: LazyView(lazyDestination), isActive: isActive)
}
init<V, S>(_ title: S, lazyDestination: @escaping @autoclosure () -> V, isActive: Binding<Bool>)
where S : StringProtocol, Destination == LazyView<V> {
self.init(title, destination: LazyView(lazyDestination), isActive: isActive)
}
init<V, T>(_ titleKey: LocalizedStringKey, lazyDestination: @escaping @autoclosure () -> V, tag: T, selection: Binding<T?>)
where T : Hashable, Destination == LazyView<V> {
self.init(titleKey, destination: LazyView(lazyDestination), tag: tag, selection: selection)
}
init<V, S, T>(_ title: S, lazyDestination: @escaping @autoclosure () -> V, tag: T, selection: Binding<T?>)
where S : StringProtocol, T : Hashable, Destination == LazyView<V> {
self.init(title, destination: LazyView(lazyDestination), tag: tag, selection: selection)
}
}
Then in your code, replace with
NavigationLink(lazyDestination: RoomView(roomId: UUID().uuidString)) {
Text("Create a new Room and enter")
}