How to navigate to a new view from navigationBar button click in SwiftUI - swift

Learning to SwiftUI. Trying to navigate to a new view from navigation bar buttton clicked.
The sample code below:
var body: some View {
NavigationView {
List(0...< 5) { item in
NavigationLink(destination: EventDetails()){
EventView()
}
}
.navigationBarTitle("Events")
.navigationBarItems(trailing:
NavigationLink(destination: CreateEvent()){
Text("Create Event")
}
)
}
}

Three steps got this working for me : first add an #State Bool to track the showing of the new view :
#State var showNewView = false
Add the navigationBarItem, with an action that sets the above property :
.navigationBarItems(trailing:
Button(action: {
self.showNewView = true
}) {
Text("Go To Destination")
}
)
Finally add a navigation link somewhere in your view code (this relies on also having a NavigationView somewhere in the view stack)
NavigationLink(
destination: MyDestinationView(),
isActive: $showNewView
) {
EmptyView()
}.isDetailLink(false)

Put the NavigationLink into the label of a button.
.navigationBarItems(
trailing: Button(action: {}, label: {
NavigationLink(destination: NewView()) {
Text("")
}
}))

This works for me:
.navigationBarItems(trailing: HStack { AddButton(destination: EntityAddView()) ; EditButton() } )
Where:
struct AddButton<Destination : View>: View {
var destination: Destination
var body: some View {
NavigationLink(destination: self.destination) { Image(systemName: "plus") }
}
}

It is an iOS13 bug at the moment: https://forums.developer.apple.com/thread/124757
The "sort-of" workaround can be found here: https://stackoverflow.com/a/57837007/4514671
Here is my solution:
MasterView -
import SwiftUI
struct MasterView: View {
#State private var navigationSelectionTag: Int? = 0
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DestinationView(), tag: 1, selection: self.$navigationSelectionTag) {
EmptyView()
}
Spacer()
}
.navigationBarTitle("Master")
.navigationBarItems(trailing: Button(action: {
self.navigationSelectionTag = 1
}, label: {
Image(systemName: "person.fill")
}))
}
}
}
struct MasterView_Previews: PreviewProvider {
static var previews: some View {
MasterView()
}
}
And the DetailsView -
import SwiftUI
struct DetailsView: View {
var body: some View {
Text("Hello, Details!")
}
}
struct DetailsView_Previews: PreviewProvider {
static var previews: some View {
DetailsView()
}
}

Related

How to make Sidebar row remember its previous detail view progress for split view SwiftUI Mac catalyst?

I am creating Split View with NavigationView in SwiftUI MacCatalyst. In sidebar (master view), I have two rows: 'Add' and 'Profile'. Tapping on them changes the detail view.
Suppose I click on 'Add' row, I see AddView() in detail view.
Then I tap 'Next 1' button to show 'TempView 1' on navigation stack.
Now, I tap on 'Profile' row in sidebar.
And when I tap one 'Add' row in sidebar again, I see this:
instead of this:
Does anyone know how to preserve row stages for SplitView in SwiftUI? My sample code below:
import SwiftUI
struct AddView: View {
#State var showNext = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: TempView1(), isActive: $showNext) { EmptyView() }
Button("Next 1") {
showNext = true
}
Text("Add View")
.padding()
}
}
.navigationViewStyle(.stack)
}
}
struct ProfileView: View {
#State var showNext = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: TempView2(), isActive: $showNext) { EmptyView() }
Button("Next 2") {
showNext = true
}
Text("Profile View")
}
}
.navigationViewStyle(.stack)
}
}
struct TempView1 : View {
var body: some View {
Text("Temp View 1")
}
}
struct TempView2 : View {
var body: some View {
Text("Temp View 2")
}
}
struct ContentView: View {
#State var showAddView = false
#State var showProfileView = false
#State var selectedRow = -1
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: AddView(), isActive: $showAddView) { EmptyView() }
NavigationLink(destination: ProfileView(), isActive: $showProfileView) { EmptyView() }
List {
Text("Add")
.padding()
.background(selectedRow == 0 ? Color.yellow : Color.clear)
.onTapGesture {
selectedRow = 0
showAddView = true
}
Text("Profile")
.padding()
.background(selectedRow == 1 ? Color.yellow : Color.clear)
.onTapGesture {
selectedRow = 1
showProfileView = true
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

How to navigate with a custom button without changing styling?

If I don't use .disabled(true) then the button does not navigate. If I used .disabled(true) then the style changes to make the foreground a grayed version of the foreground color. I want to navigate without changing the style of my custom button. I used a non-custom button in the example to save space.
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: ContentView2(),
label: {
Button(action: {}, label: {
Text("Button")
}).disabled(true)
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ContentView2: View {
var body: some View {
Text("wdfokjokjokjokjwdofjk")
.padding()
}
}
Instead of making your own Button, just use Text. When you are doing .disabled(true) to make a button active, something is definitely wrong...
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: ContentView2()) {
Text("Button")
}
}
}
}
You can use an isActive parameter for the NavigationLink and set it as an invisible background or overlay:
struct ContentView: View {
#State private var navLinkActive = false
var body: some View {
NavigationView {
Button(action: {
navLinkActive = true
}, label: {
Text("Button")
})
.buttonStyle(CustomButtonStyle())
.background(NavigationLink(
destination: ContentView2(),
isActive: $navLinkActive,
label: {
EmptyView()
}))
}
}
}
struct CustomButtonStyle : ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(configuration.isPressed ? Color.red : Color.green)
}
}

If you cancel the process of returning to the previous screen by swiping, the navigationBar remains without disappearing

When swiping from the View with navigationBarItems, canceling the swipe and returning to the previous screen, the navigationBar on the previous screen remained without disappearing.
Is this a bug?
Or is my implementation wrong?
You can check the phenomenon here.
struct TopView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailView()) {
Text("Detail")
}
}
.navigationBarTitle("Top")
}
}
}
struct DetailView: View {
var body: some View {
VStack {
NavigationLink(destination: EditView()) {
Text("Edit")
}
}
.navigationBarTitle("Detail", displayMode: .inline)
}
}
struct EditView: View {
#Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("Title")
}
.navigationBarTitle("Edit", displayMode: .inline)
.navigationBarItems(
trailing:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Save")
}
)
}
}
#Environment (. PresentationMode) private var presentationMode:
Binding
If this were not present, it would not occur.
Here is fix
struct DetailView: View {
var body: some View {
VStack {
NavigationLink(destination: EditView()) {
Text("Edit")
}.isDetailLink(false) // << here !!
}
.navigationBarTitle("Detail", displayMode: .inline)
}
}

Pop to root view using Tab Bar in SwiftUI

Is there any way to pop to root view by tapping the Tab Bar like most iOS apps, in SwiftUI?
Here's an example of the expected behavior.
I've tried to programmatically pop views using simultaneousGesture as follow:
import SwiftUI
struct TabbedView: View {
#State var selection = 0
#Environment(\.presentationMode) var presentationMode
var body: some View {
TabView(selection: $selection) {
RootView()
.tabItem {
Image(systemName: "house")
.simultaneousGesture(
TapGesture().onEnded {
self.presentationMode.wrappedValue.dismiss()
print("View popped")
}
)
}.tag(0)
Text("")
.tabItem {
Image(systemName: "line.horizontal.3")
}.tag(1)
}
}
}
struct RootView: View {
var body: some View {
NavigationView {
NavigationLink(destination: SecondView()) {
Text("Go to second view")
}
}
}
}
struct SecondView: View {
var body: some View {
Text("Tapping the house icon should pop back to root view")
}
}
But seems like those gestures were ignored.
Any suggestions or solutions are greatly appreciated
We can use tab bar selection binding to get the selected index. On this binding we can check if the tab is already selected then pop to root for navigation on selection.
struct ContentView: View {
#State var showingDetail = false
#State var selectedIndex:Int = 0
var selectionBinding: Binding<Int> { Binding(
get: {
self.selectedIndex
},
set: {
if $0 == self.selectedIndex && $0 == 0 && showingDetail {
print("Pop to root view for first tab!!")
showingDetail = false
}
self.selectedIndex = $0
}
)}
var body: some View {
TabView(selection:selectionBinding) {
NavigationView {
VStack {
Text("First View")
NavigationLink(destination: DetailView(), isActive: $showingDetail) {
Text("Go to detail")
}
}
}
.tabItem { Text("First") }.tag(0)
Text("Second View")
.tabItem { Text("Second") }.tag(1)
}
}
}
struct DetailView: View {
var body: some View {
Text("Detail")
}
}
I messed around with this for a while and this works great. I combined answers from all over and added some stuff of my own. I'm a beginner at Swift so feel free to make improvements.
Here's a demo.
This view has the NavigationView.
import SwiftUI
struct AuthenticatedView: View {
#StateObject var tabState = TabState()
var body: some View {
TabView(selection: $tabState.selectedTab) {
NavigationView {
NavigationLink(destination: TestView(titleNum: 0), isActive: $tabState.showTabRoots[0]) {
Text("GOTO TestView #1")
.padding()
.foregroundColor(Color.white)
.frame(height:50)
.background(Color.purple)
.cornerRadius(8)
}
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
}
.navigationViewStyle(.stack)
.onAppear(perform: {
tabState.lastSelectedTab = TabState.Tab.first
}).tabItem {
Label("First", systemImage: "list.dash")
}.tag(TabState.Tab.first)
NavigationView {
NavigationLink(destination: TestView(titleNum: 0), isActive: $tabState.showTabRoots[1]) {
Text("GOTO TestView #2")
.padding()
.foregroundColor(Color.white)
.frame(height:50)
.background(Color.purple)
.cornerRadius(8)
}.navigationTitle("")
.navigationBarTitleDisplayMode(.inline).navigationBarTitle(Text(""), displayMode: .inline)
}
.navigationViewStyle(.stack)
.onAppear(perform: {
tabState.lastSelectedTab = TabState.Tab.second
}).tabItem {
Label("Second", systemImage: "square.and.pencil")
}.tag(TabState.Tab.second)
}
.onReceive(tabState.$selectedTab) { selection in
if selection == tabState.lastSelectedTab {
tabState.showTabRoots[selection.rawValue] = false
}
}
}
}
struct AuthenticatedView_Previews: PreviewProvider {
static var previews: some View {
AuthenticatedView()
}
}
class TabState: ObservableObject {
enum Tab: Int, CaseIterable {
case first = 0
case second = 1
}
#Published var selectedTab: Tab = .first
#Published var lastSelectedTab: Tab = .first
#Published var showTabRoots = Tab.allCases.map { _ in
false
}
}
This is my child view
import SwiftUI
struct TestView: View {
let titleNum: Int
let title: String
init(titleNum: Int) {
self.titleNum = titleNum
self.title = "TestView #\(titleNum)"
}
var body: some View {
VStack {
Text(title)
NavigationLink(destination: TestView(titleNum: titleNum + 1)) {
Text("Goto View #\(titleNum + 1)")
.padding()
.foregroundColor(Color.white)
.frame(height:50)
.background(Color.purple)
.cornerRadius(8)
}
NavigationLink(destination: TestView(titleNum: titleNum + 100)) {
Text("Goto View #\(titleNum + 100)")
.padding()
.foregroundColor(Color.white)
.frame(height:50)
.background(Color.purple)
.cornerRadius(8)
}
.navigationTitle(title)
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView(titleNum: 0)
}
}
You can achieve this by having the TabView within a NavigationView like so:
struct ContentView: View {
#State var selection = 0
var body: some View {
NavigationView {
TabView(selection: $selection) {
FirstTabView()
.tabItem {
Label("Home", systemImage: "house")
}
.tag(0)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct FirstTabView: View {
var body: some View {
NavigationLink("SecondView Link", destination: SecondView())
}
}
struct SecondView: View {
var body: some View {
Text("Second View")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ContentView()
}
}
}

Button, how to open a new View in swiftUI embedded in navigation bar

I embedded a button on on the NavigationBar.
I'm try to make button to open a new View called DetailView
I try to use NavigationLink but it does't work inside a button.
import SwiftUI
struct ContentView: View {
#ObservedObject var dm: DataManager
#State var isAddPresented = false
var body: some View {
NavigationView {
HStack {
List () {
ForEach (dm.storage) { data in
StileCella(dm2: data)
}
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(trailing: Button(action: {
self.isAddPresented = true
// Load here the DetailView??? How??
DetailView()
}) {
Text("Button")
})
}
}
}
}
struct DetailView: View {
var body: some View {
VStack(alignment: .center) {
Text("CIAO").bold()
Spacer()
Image(systemName: "star")
.resizable()
}
}
}
You just need to add a sheet modifier to your view, which presents your view depending on the value of isAddPresented, just like this:
struct ContentView: View {
#State var isAddPresented = false
var body: some View {
NavigationView {
List(dm.storage){ data in
StileCella(dm2: data)
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(trailing: Button("Button") {
self.isAddPresented = true
})
} .sheet(isPresented: $isAddPresented,
onDismiss: { self.isAddPresented = false }) {
DetailView()
}
}
}
The important bit is to remember to set isAddPresented back to false in on dismiss to prevent it form presenting again.
If you want to open a new view just like we used to open through storyboard other than sheet, you can update the code in the following way:
import SwiftUI
struct ContentView: View {
#ObservedObject var dm: DataManager
#State var isAddPresented = false
var body: some View {
NavigationView {
HStack {
List () {
ForEach (dm.storage) { data in
StileCella(dm2: data)
}
}
.navigationBarTitle("Lista Rubrica")
.navigationBarItems(leading:
NavigationLink(destination: DetailView()) {
Text("Button")
})
}
}
}
}
struct DetailView: View {
var body: some View {
VStack(alignment: .center) {
Text("CIAO").bold()
Spacer()
Image(systemName: "star")
.resizable()
}
}
}
Instead of button, simply add NavigationLink inside navigationBarItems. This would do the trick! I wrote the complete for guidance but main change point is, I used
.navigationBarItems(leading:
NavigationLink(destination: DetailView()) {
Text("Button")
})
instead of:
.navigationBarItems(trailing: Button(action: {
self.isAddPresented = true
// Load here the DetailView??? How??
DetailView()
}) {
Text("Button")
})