Navigation not working in SwiftUI - Pop to a specific view - ios

I am trying to pop to a specific view using the isActive binding of NavigationLink of SwiftUI. Here is my code:
struct Root: View
{
#Environment(\.dismiss) var dismissValue: DismissAction
#State var rootToView1Navigattion: Bool = false
var body: some View
{
HStack
{
NavigationLink(isActive: $rootToView1Navigattion) {
View1()
} label: {
EmptyView()
}
Button {
dismissValue()
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
Button {
rootToView1Navigattion = true
} label: {
Text("Go Forward")
.font(.title3)
.padding()
.background(Color.green)
}
}
.navigationTitle(String(describing: Self.self))
}
}
struct View1: View
{
#Environment(\.dismiss) var dismissValue: DismissAction
#State var view1ToView2Navigation: Bool = false
var body: some View
{
HStack
{
NavigationLink(isActive: $view1ToView2Navigation) {
View2(view1ToView2NavBinding: $view1ToView2Navigation)
} label: {
EmptyView()
}
Button {
dismissValue()
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
Button {
view1ToView2Navigation = true
} label: {
Text("Go Forward")
.font(.title3)
.padding()
.background(Color.green)
}
}
.navigationTitle(String(describing: Self.self))
}
}
struct View2: View
{
#Binding var view1ToView2NavBinding: Bool
var body: some View
{
HStack
{
Button {
view1ToView2NavBinding = false
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
}
.navigationTitle(String(describing: Self.self))
}
}
As per my concept, View1 has a property view1ToView2Navigation, which is passed to isActive param of NavigationLink. And this property is passed as binding to View2. When I set it false in View2, everything above View1 should dismiss. But this is not working, Am I missing out something conceptually ??
My RootView is enclosed in a NavigationView. And When I do the same between Root and View1. It works smoothly.

Edited: Based on your new comment, you want to navigate back to root from view 2.
Try the below code. When you press the yellow back button in view2, you will be navigated back to root.
import SwiftUI
struct ContentView: View
{
#Environment(\.dismiss) var dismissValue: DismissAction
#State var toRoot = false
var body: some View
{
NavigationView
{
HStack {
Button {
dismissValue()
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
NavigationLink {
View1(toRoot: $toRoot)
} label: {
Text("Go Forward")
.font(.title3)
.padding()
.background(Color.green)
}
}
}
.navigationTitle(String(describing: Self.self))
}
}
struct View1: View
{
#Environment(\.dismiss) var dismissValue: DismissAction
#Binding var toRoot: Bool
var body: some View
{
HStack
{
Button {
dismissValue()
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
NavigationLink {
View2(toRoot: $toRoot)
} label: {
Text("Go Forward")
.font(.title3)
.padding()
.background(Color.green)
}
}
.navigationTitle(String(describing: Self.self))
.onAppear {
if toRoot {
dismissValue()
}
}
}
}
struct View2: View
{
#Binding var toRoot: Bool
#Environment(\.dismiss) var dismissValue: DismissAction
var body: some View
{
HStack
{
Button {
toRoot = true
dismissValue()
} label: {
Text("Go Back")
.font(.title3)
.padding()
.background(Color.yellow)
}
}
.navigationTitle(String(describing: Self.self))
}
}

Related

SwiftUI - Remove extra space in NavigationBar after transitioning back to Home view from subview

I am new to SwiftUI and have run into a little challenge. Whenever I go from my Home view to a sub-view and then back to the Home view, I am seeing extra space created in the Navigation view (see linked GIF). I was wondering if anyone had any advice - thanks in advance!
Here is the Home Screen:
struct Home: View {
#State private var view2 = false
var body: some View {
NavigationView {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
} }
Here is the sub-new (View2):
struct View2: View {
#State private var home = false
var body: some View {
VStack {
Text("This is View 2")
.padding()
NavigationLink(destination: Home().navigationBarBackButtonHidden(true), isActive: $home) { }
Button {
self.home = true
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 1")
} }
Link to GIF:
Visual GIF of the issue
Every time you push a new Home via a NavigationLink, you're adding another NavigationView to the hierarchy, since Home has a NavigationView in it.
To avoid that, you could separate the NavigationView out and instead link to View:
struct Home: View {
var body: some View {
NavigationView {
View1() //<-- Here
}
}
}
struct View1 : View {
#State private var view2 = false
var body: some View {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
}
struct View2: View {
#State private var home = false
var body: some View {
VStack {
Text("This is View 2")
.padding()
NavigationLink(destination: View1() //<-- Here
.navigationBarBackButtonHidden(true), isActive: $home) { }
Button {
self.home = true
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 2")
}
}
That being said, I'm a little skeptical of the strategy here. It seems like instead of pushing a new View1, you might just want to be going back to the existing one. In that case, your code could just look like this:
struct Home: View {
var body: some View {
NavigationView {
View1()
}
}
}
struct View1 : View {
#State private var view2 = false
var body: some View {
VStack {
Text("Home View!")
.padding()
NavigationLink(destination: View2(), isActive: $view2) { }
Button {
self.view2 = true
} label: {
Text("Go to next view")
}
}
.navigationTitle("Home")
}
}
struct View2: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text("This is View 2")
.padding()
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Text("Go to Home view")
}
}
.navigationTitle("View 2")
}
}

How can I go to a view by clicking on a Button in SwiftUI

If the user clicks on connexionBtnView I want to redirect them to an AdminView or UserView
import SwiftUI
struct ConnexionView: View {
#State var loginId: String = ""
#State var pwd: String = ""
#StateObject private var keyboardHander = KeyBoardHandler()
var body: some View {
NavigationView{
ZStack{
Image("background")
.ignoresSafeArea()
VStack (spacing: 15){
Spacer()
logoView
Spacer()
titleView
loginIdView
loginPwdView
connexionBtnView
Spacer()
NavigationLink {
LostPwdView()
} label: {
lostPwd
}
Spacer()
}.frame(maxHeight: .infinity)
.padding(.bottom,keyboardHander.keyboardHeight)
.animation(.default)
}
}
}
The NavigationLink has the isActive parameter. You can pass it in the init of NavigationLink and when this state variable has the true value you will redirect to another view. Details here.
struct ConnexionView: View {
#State var isActive: Bool = false
var body: some View {
NavigationView {
VStack {
NavigationLink(isActive: $isActive) {
LostPwdView()
} label: {
Text("Some Label")
}
Button("Tap me!") {
isActive = true
}
}
}
}
}
struct LostPwdView: View {
var body: some View {
Text("Hello")
}
}
What you need to do is having a #State variable that would trigger the navigation:
.fullScreenCover(
isPresented: $viewShown
) {
print("View dismissed")
} content: {
NextView()
}
Where NextView() is the View you want to show and the viewShown is your State variable, below a full example:
struct ExampleView: View {
#State var isNextPageOpen = false
var body: some View {
Button("Tap Here To Navigate") {
isNextPageOpen = true
}
.fullScreenCover(
isPresented: $isNextPageOpen
) {
print("View dismissed")
} content: {
NextView()
}
}
}

Show different views from NavigationBarItem menu in SwiftUI

I am trying to show a different view based on the option chosen in the NavigationBar menu. I am getting stuck on the best way to do this.
First, based on my current approach (I think it is not right!), I get a message in Xcode debugger when I press the menu item:
SideMenu[16587:1131441] [UILog] Called -[UIContextMenuInteraction
updateVisibleMenuWithBlock:] while no context menu is visible. This
won't do anything.
How do I fix this?
Second, When I select an option from the menu, how do I reset the bool so that it does not get executed unless it is chosen from the menu again. Trying to reset as self.showNewView = false within the if condition gives a compiler error
Here is a full executable sample code I am trying to work with. Appreciate any help in resolving this. Thank you!
struct ContentView: View {
#State var showNewView = false
#State var showAddView = false
#State var showEditView = false
#State var showDeleteView = false
var body: some View {
NavigationView {
GeometryReader { g in
VStack {
if self.showAddView {
AddView()
}
if self.showNewView {
NewView()
}
if self.showEditView {
EditView()
}
if self.showDeleteView {
DeleteView()
}
}.frame(width: g.size.width, height: g.size.height)
}
.navigationTitle("Title")
.navigationBarItems(leading: {
Menu {
Button(action: {showNewView.toggle()}) {
Label("New", systemImage: "pencil")
}
Button(action: {showEditView.toggle()}) {
Label("Edit", systemImage: "square.and.pencil")
}
} label: {
Image(systemName: "ellipsis.circle")
}
}(), trailing: {
Menu {
Button(action: {showAddView.toggle()}) {
Label("Add", systemImage: "plus")
}
Button(action: {showDeleteView.toggle()}) {
Label("Delete", systemImage: "trash")
}
} label: {
Image(systemName: "plus")
}
}())
}
.navigationBarTitleDisplayMode(.inline)
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct NewView: View {
var body: some View {
GeometryReader { g in
Text("This is New View")
}
.background(Color.red)
}
}
struct EditView: View {
var body: some View {
GeometryReader { g in
Text("This is Edit View")
}
.background(Color.green)
}
}
struct AddView: View {
var body: some View {
GeometryReader { g in
Text("This is Add View")
}
.background(Color.orange)
}
}
struct DeleteView: View {
var body: some View {
GeometryReader { g in
Text("This is Delete View")
}
.background(Color.purple)
}
}
Here is what I get when I select each of the menu items. I would like to be able to show only one menu item. Essentially dismiss the other one when a new menu item is selected
A possible solution is to use a dedicated enum for your current view (instead of four #State properties):
enum CurrentView {
case new, add, edit, delete
}
#State var currentView: CurrentView?
Note that you can also extract parts of code to computed properties.
Here is a full code:
enum CurrentView {
case new, add, edit, delete
}
struct ContentView: View {
#State var currentView: CurrentView?
var body: some View {
NavigationView {
GeometryReader { g in
content
.frame(width: g.size.width, height: g.size.height)
}
.navigationTitle("Title")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(leading: leadingBarItems, trailing: trailingBarItems)
}
.navigationViewStyle(StackNavigationViewStyle())
}
#ViewBuilder
var content: some View {
if let currentView = currentView {
switch currentView {
case .add:
AddView()
case .new:
NewView()
case .edit:
EditView()
case .delete:
DeleteView()
}
}
}
var leadingBarItems: some View {
Menu {
Button(action: { currentView = .new }) {
Label("New", systemImage: "pencil")
}
Button(action: { currentView = .edit }) {
Label("Edit", systemImage: "square.and.pencil")
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
var trailingBarItems: some View {
Menu {
Button(action: { currentView = .add }) {
Label("Add", systemImage: "plus")
}
Button(action: { currentView = .delete }) {
Label("Delete", systemImage: "trash")
}
} label: {
Image(systemName: "plus")
}
}
}

How can I hide TabBar Swift UI?

I have a TabBarView in the root view. In one of the parent views that's nested within the root view, I'd like the tab bar to hide when navigating from that parent view to the child view. Is there any func or command to handle that?
Something like this:
ContentView (with TabBarView) - > ExploreView (Called in TabBarView ) -> MessagesView (Child of ExploreVIew - Hide Tab bar)
My code can be seen below.
TabView{
NavigationView{
GeometryReader { geometry in
ExploreView()
.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(leading: Button(action: {
}, label: {
HStack{
Image("cityOption")
Text("BER")
Image("arrowCities")
}.foregroundColor(Color("blackAndWhite"))
.font(.system(size: 12, weight: .semibold))
}),trailing:
HStack{
Image("closttop")
.renderingMode(.template)
.padding(.trailing, 125)
NavigationLink(destination: MessagesView()
.navigationBarTitle(Text("Messages"), displayMode: .inline)
.navigationBarItems(trailing: Image("writemessage"))
.foregroundColor(Color("blackAndWhite"))
){
Image("messages")
}
}.foregroundColor(Color("blackAndWhite"))
)
}
}
.tabItem{
HStack{
Image("clostNav").renderingMode(.template)
Text("Explore")
.font(.system(size: 16, weight: .semibold))
}.foregroundColor(Color("blackAndWhite"))
}
SearchView().tabItem{
Image("search").renderingMode(.template)
Text("Search")
}
PostView().tabItem{
HStack{
Image("post").renderingMode(.template)
.resizable().frame(width: 35, height: 35)
}
}
OrdersView().tabItem{
Image("orders").renderingMode(.template)
Text("Orders")
}
ProfileView().tabItem{
Image("profile").renderingMode(.template)
Text("Profile")
}
}
Appreciate any help! Thanks!
Create CustumPresentViewController.swift -
import UIKit
import SwiftUI
struct ViewControllerHolder {
weak var value: UIViewController?
}
struct ViewControllerKey: EnvironmentKey {
static var defaultValue: ViewControllerHolder { return
ViewControllerHolder(value:
UIApplication.shared.windows.first?.rootViewController ) }
}
extension EnvironmentValues {
var viewController: ViewControllerHolder {
get { return self[ViewControllerKey.self] }
set { self[ViewControllerKey.self] = newValue }
}
}
extension UIViewController {
func present<Content: View>(style: UIModalPresentationStyle =
.automatic, #ViewBuilder builder: () -> Content) {
// Must instantiate HostingController with some sort of view...
let toPresent = UIHostingController(rootView:
AnyView(EmptyView()))
toPresent.modalPresentationStyle = style
// ... but then we can reset rootView to include the environment
toPresent.rootView = AnyView(
builder()
.environment(\.viewController, ViewControllerHolder(value:
toPresent))
)
self.present(toPresent, animated: true, completion: nil)
}
}
Use this in required View -
#Environment(\.viewController) private var viewControllerHolder:
ViewControllerHolder
private var viewController: UIViewController? {
self.viewControllerHolder.value
}
var body: some View {
NavigationView {
ZStack {
Text("Navigate")
}.onTapGesture {
self.viewController?.present(style: .fullScreen) {
EditUserView()
}
}
}
}
A bit late here, on iOS 16 you could use ContentView().toolbar(
.hidden, for: .tabBar)
So in your case, it would be like as below,
struct ExploreView: View {
var body: some View {
some_view {
}
.toolbar(.hidden, for: .tabBar)
}
}
in a normal iphone environment the tabbar vanishes from itself if you are navigating....or are u running in another environment?
check this:
struct ContentView: View {
#State var hideTabbar = false
#State var navigate = false
var body: some View {
NavigationView {
TabView {
VStack {
NavigationLink(destination: Text("without tab")){
Text("aha")
}
.tabItem {
Text("b")
}
}.tag(0)
Text("Second View")
.tabItem {
GeometryReader { geometry in
Image(systemName: "2.circle")
// Text("Second")
Text("\(geometry.size.height) - \(geometry.size.width)")
}
}.tag(1)
}
}
}//.isHidden(self.hideTabbar)
}

SwiftUI How to push to next screen when tapping on Button

I can navigate to next screen by using NavigationButton (push) or present with PresentationButton (present) but i want to push when i tap on Buttton()
Button(action: {
// move to next screen
}) {
Text("See More")
}
is there a way to do it?
You can do using NavigationLink
Note: Please try in real device. in simulator sometimes not work properly.
struct MasterView: View {
#State var selection: Int? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
Button("Press me") {
self.selection = 1
}
}
}
}
}
}
struct DetailsView: View {
#Environment(\.presentationMode) var presentation
var body: some View {
Group {
Button("Go Back") {
self.presentation.wrappedValue.dismiss()
}
}
}
}
As you can see to display the new view, add the NavigationLink with isActive: $pushView using <.hidden()> to hide the navigation "arrow".
Next add Text("See More") with tapGesture to make the text respond to taps. The variable pushView will change (false => true) when you click "See More" text.
import SwiftUI
struct ContentView: View {
#State var pushView = false
var body: some View {
NavigationView {
List {
HStack{
Text("test")
Spacer()
NavigationLink(destination: NewView(), isActive: $pushView) {
Text("")
}.hidden()
.navigationBarTitle(self.pushView ? "New view" : "default view")
Text("See More")
.padding(.trailing)
.foregroundColor(Color.blue)
.onTapGesture {
self.pushView.toggle()
}
}
}
}
}
}
struct NewView: View {
var body: some View {
Text("New View")
}
}
ContentView picture
NewView picture
To tap on button and navigate to next screen,You can use NavigationLink like below
NavigationView{
NavigationLink(destination: SecondView()) {
Text("Login")
.padding(.all, 5)
.frame(minWidth: 0, maxWidth: .infinity,maxHeight: 45, alignment: .center)
.foregroundColor(Color.white)
}
}
You can use NavigationLink to implement this:
struct DetailsView: View {
var body: some View {
VStack {
Text("Hello world")
}
}
}
struct ContentView: View {
#State var selection: Int? = nil
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
Button("Press me") {
self.selection = 1
}
}
}
}
}
}

Resources