SwiftUI: Empty Detail View After Second NavigationLink - swiftui

there is an interesting bug after the iOS 15 release. It was working well till iOS 15 but something went wrong after it.
I have a drawer menu, when users click on a category, I trigger hidden NavigationLink to go to the category page. There is no problem till here. It's occurring when users click on the news to go to the detail. It's showing only a blank page. When I add NavigationLink scope to top-level on CategoryView it's working fine but this time there are two navigations on the page on the same page.
CategoryView
var body: some View {
ZStack{ // When I change this with NavigationLink it's working well
if viewModel.news.count > 0 {
List{
ForEach(Array(self.viewModel.news.enumerated()), id: \.1) { index, element in
NavigationLink(
destination: LazyView(HaberDetay(id: .constant(element.id), type: .constant(element.rights ?? ""))),
label: {
UI codes....
})
.onAppear {
self.viewModel.loadMoreArticles(currentItem: element, id: self.id)
}
}
}.listStyle(PlainListStyle())
}else{
Group{
if viewModel.error == true{
ConnectionError()
}else{
LoadingView()
}
}
}
}
.onAppear(){
self.viewModel.loadMoreArticles(id: self.id)
}
.navigationBarTitle(Text(title), displayMode: .inline)
}
ContentView
#ViewBuilder
func buildView() -> some View {
switch self.menuVM.option {
case "new":
HaberDetay(id: self.$selectedNew, type: self.$selectedNewType)
case "category":
CategoryView(id: self.$menuVM.selectedCatID, title: self.$menuVM.selectedCatTitle, icon: self.$menuVM.selectedCatIcon)
case "page":
PageView(title: $menuVM.pageTitle, content: $menuVM.pageContent, icon: .constant(""))
case "table":
PuanDurumu()
default:
EmptyView()
}
}
var body: some View {
SideMenu(content: AnyView(
NavigationView{
ZStack{
NavigationLink(destination: LazyView(self.buildView()), isActive: $menuVM.showDetail) {
EmptyView()
}.hidden()
UI Codes...
}
.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(leading: Image("orta").resizable().foregroundColor(Color(UIColor(named: "DarkColor")!))
.frame(width: 34, height: 34), trailing: Button(action: {
withAnimation{
self.isDrawerOpen.toggle()
}
}) {
Image(systemName: "text.alignright").renderingMode(.template).foregroundColor(Color(UIColor(named: "DarkColor")!))
})
}.phoneOnlyStackNavigationView()
.onAppear(){
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.backgroundColor = UIColor.systemBackground
UINavigationBar.appearance().standardAppearance = navBarAppearance
if self.menuVM.menu.count == 0 {
self.menuVM.fetchMenu()
}
self.sliderVM.fetchSliderNews()
self.otherVM.selected = 0
}), isPresented: $isDrawerOpen)
}
phoneOnlyStackNavigationView Extension:
extension View{
func phoneOnlyStackNavigationView() ->some View{
if UIDevice.current.userInterfaceIdiom == .phone{
return AnyView(self.navigationViewStyle(DefaultNavigationViewStyle()))
}else{
return AnyView(self.navigationViewStyle(StackNavigationViewStyle()))
}
}
}
I researched it a lot but it seems no one faced with this issue, as I said before it occurred automatically after iOS 15 :(

Related

Navigation repeats itself several times after clicking the object

I just shared this Bug with Apple. I want to share with you.
Application Follow
1 - After the user logs on to the onBoardingView page, they are directed to ContentView with fullScreenCover.
2 - ContentView page contains objects in TabView that are repeated with ForEach. Clicking on these objects will take you to the DetailView page.
3 - However, Navigation repeats itself several times after clicking the object.
My English is bad. Sorry for this.
Video is here
Project file is here
struct OnboardView: View {
#State var isLogin: Bool = false
var body: some View {
Button(action: {self.isLogin = true}) {
Text("Login")
}
.fullScreenCover(isPresented: self.$isLogin) {
ContentView()
}
}
}
struct ContentView: View {
#State var selected: String = ""
var items: [String] = ["1","2","3","4","5","6","7","8","9","10"]
var body: some View {
NavigationView {
TabView(selection: $selected) {
ForEach(items, id: \.self) { item in
NavigationLink(
destination: DetailView(),
label: {
Text(item)
.foregroundColor(.white)
.padding()
.background(Color.orange)
.cornerRadius(10)
})
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
}
}
}
When working with ForEach in SwiftUI, you have to be extra careful on the ids.
Try changing items to items.indices instead:
ForEach(items.indices, id: \.self) { item in
NavigationLink(
destination: Text("Detail View"),
label: {
Text(items[item])
.foregroundColor(.white)
.padding()
.background(Color.orange)
.cornerRadius(10)
}
)
}

Crash when using hiding a ProgressView in a Picker label

I am trying to put a ProgressView inside a Picker label. When I tap the Hide Spinner button, this (intermittently) crashes with EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
struct ContentView: View {
#State private var selectedCity = ""
#State private var showSpinner = true
let cities = [
"Calgary",
"Edmonton",
"Toronto"
]
var body: some View {
NavigationView {
VStack(spacing: 0) {
Form {
Picker(selection: $selectedCity, label:
HStack {
Text("Your City")
if showSpinner {
ProgressView()
.padding(.horizontal, 2)
}
}
) {
ForEach(cities, id: \.self) { city in
Text(city).tag(city)
}
}
Button("Hide Spinner", action: { showSpinner = false })
}
}
.navigationBarTitle("ProgressView Crash", displayMode: .inline)
}
}
}
Am I doing anything wrong? I'm guessing this is a SwiftUI bug. I get the same behaviour when wrapping a UIActivityIndicatorView in a UIViewRepresentable.
Yes, it looks like a bug with auto-generated accessibility label. The safe workaround is to use explicitly provided accessibility.
Tested with Xcode 12 / iOS 14
Picker(selection: $selectedCity, label:
HStack {
Text("Your City")
if showSpinner {
ProgressView()
.padding(.horizontal, 2)
}
}.accessibility(label: Text("Your City")) // << here !!
) {
ForEach(cities, id: \.self) { city in
Text(city).tag(city)
}
}

How to perform an action after NavigationLink is tapped?

I have a Plus button in my first view. Looks like a FAB button. I want to hide it after I tap some step wrapped in NavigationLink. So far I have something like this:
ForEach(0 ..< 12) {item in
NavigationLink(destination: TransactionsDetailsView()) {
VStack {
HStack(alignment: .top) {
Text("List item")
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
}
.simultaneousGesture(TapGesture().onEnded{
self.showPlusButton = false
})
.onAppear(){
self.showPlusButton = true
}
}
It works fine with single tap. But when I long press NavigationLink it doesn't work. How should I rewrite my code to include long press as well? Or maybe I should make it work different than using simultaneousGesture?
I'm using the following code. I prefer it to just NavigationLink by itself because it lets me reuse my existing ButtonStyles.
struct NavigationButton<Destination: View, Label: View>: View {
var action: () -> Void = { }
var destination: () -> Destination
var label: () -> Label
#State private var isActive: Bool = false
var body: some View {
Button(action: {
self.action()
self.isActive.toggle()
}) {
self.label()
.background(
ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
NavigationLink(destination: LazyDestination { self.destination() },
isActive: self.$isActive) { EmptyView() }
}
)
}
}
}
// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
var destination: () -> Destination
var body: some View {
self.destination()
}
}
And to use it:
var body: some View {
NavigationButton(
action: { print("tapped!") },
destination: { Text("Pushed View") },
label: { Text("Tap me") }
)
}
Yes, NavigationLink does not allow such simultaneous gestures (might be as designed, might be due to issue, whatever).
The behavior that you expect might be implemented as follows (of course if you need some chevron in the list item, you will need to add it manually)
struct TestSimultaneousGesture: View {
#State var showPlusButton = false
#State var currentTag: Int?
var body: some View {
NavigationView {
List {
ForEach(0 ..< 12) { item in
VStack {
HStack(alignment: .top) {
Text("List item")
NavigationLink(destination: Text("Details"), tag: item, selection: self.$currentTag) {
EmptyView()
}
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
self.currentTag = item
self.showPlusButton = false
})
.simultaneousGesture(LongPressGesture().onEnded{_ in
print("Got Long Press")
self.currentTag = item
self.showPlusButton = false
})
.onAppear(){
self.showPlusButton = true
}
}
}
}
}
}
Another alternative I have tried. Not using simultaneousGesture, but an onDisappear modifier instead. Code is simple and It works. One downside is that those actions happen with a slight delay. Because first the destination view slides in and after this the actions are performed. This is why I still prefer #Asperi's answer where he added .simultaneousGesture(LongPressGesture) to my code.
ForEach(0 ..< 12) {item in
NavigationLink(destination: TransactionsDetailsView()) {
VStack {
HStack(alignment: .top) {
Text("List item")
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
}
.onDisappear(){
self.showPlusButton = false
}
.onAppear(){
self.showPlusButton = true
}
}
I have tried an alternative approach to solving my problem. Initially I didn't use "List" because I had a problem with part of my code. But it cause another problem: PlusButton not disappearing on next screen after tapping NavigationLink. This is why I wanted to use simultaneousGesture - after tapping a link some actions would be performed as well (here: PlusButton would be hidden). But it didn't work well.
I have tried an alternative solution. Using List (and maybe I will solve another problem later.
Here is my alternative code. simultaneousGesture is not needed at all. Chevrons are added automatically to the list. And PlusButton hides the same I wanted.
import SwiftUI
struct BookingView: View {
#State private var show_modal: Bool = false
var body: some View {
NavigationView {
ZStack {
List {
DateView()
.listRowInsets(EdgeInsets())
ForEach(0 ..< 12) {item in
NavigationLink(destination: BookingDetailsView()) {
HStack {
Text("Booking list item")
Spacer()
}
.padding()
}
}
}.navigationBarTitle(Text("Booking"))
VStack {
Spacer()
Button(action: {
print("Button Pushed")
self.show_modal = true
}) {
Image(systemName: "plus")
.font(.largeTitle)
.frame(width: 60, height: 60)
.foregroundColor(Color.white)
}.sheet(isPresented: self.$show_modal) {
BookingAddView()
}
.background(Color.blue)
.cornerRadius(30)
.padding()
.shadow(color: Color.black.opacity(0.3), radius: 3, x: 3, y: 3)
}
}
}
}
}

SwiftUI Nested NavigationView navigationBar disappears

I have a three views which are lists. struct MainMenuView: View {
#EnvironmentObject var dataModel: DM
var body: some View {
return NavigationView{
List {
Matchup()
GameSettings()
EnteringGame()
}
}
}
Inside Matchup()
struct Matchup: View {
#EnvironmentObject var dataModel: DM
var body: some View {
Section(header: Text("MATCH-UP")
.fontWeight(.heavy)
.foregroundColor(Color("TPLightGrey"))
) {
NavigationLink(destination: TrendSingleSelect(
title: .constant("TEAM"),
col: .constant(self.dataModel.queryColumnTeam1),
items: .constant(self.dataModel.team1Values) ,
selection: self.$dataModel.team1ListValue
)) {
HStack {
Text("TEAM")
Spacer()
if dataModel.team1ListValue.count == 0 {
Text("IS ANY").foregroundColor(Color("TPLightGrey"))
} else {
Text( self.dataModel.team1ListValue.joined(separator: ", ")).foregroundColor(Color("TPOrange"))
}
}
}
}
.listRowBackground(Color("TPDarkGrey"))
.font(.system(size: 14))
.navigationBarTitle("", displayMode: .inline)
.navigationBarHidden(true)
}
}
Notice that I hide theNavBar. I want to push in a nav when the user tabs a row.: Here is the final view:
var body: some View {
return VStack {
List {
ForEach(self.items, id: \.self) { item in
SingleSelectionRow(title: item, isSelected: self.selection.contains(item)) {
if self.selection.contains(item) {
self.selection = []
}
else {
self.selection = [item]
}
self.queryCallback()
}
.listRowBackground(Color("TPDarkGrey"))
}//ForEach
}//list
.font(.system(size: 14))
}
.navigationBarHidden(false)
.navigationBarTitle(title)
.navigationBarItems(trailing:
Button(action: {
// Actions
self.reset()
}, label: {
Text("Clear")
}
)
)
}
What happens is: That when I tap the sell, I push in that section. However, when it pushes in, I see the navBar, then it gets collapsed. However,when I then tap anything in the view to trigger the view reload, it shows up.
What is causing the navbar collapse?
try this code in MatchupView:
struct Matchup: View {
#EnvironmentObject var dataModel: DM
var body: some View {
NavigationView { // attention hear************
Section(header: Text("MATCH-UP")
.fontWeight(.heavy)
.foregroundColor(Color("TPLightGrey"))
) {
NavigationLink(destination: TrendSingleSelect(
title: .constant("TEAM"),
col: .constant(self.dataModel.queryColumnTeam1),
items: .constant(self.dataModel.team1Values) ,
selection: self.$dataModel.team1ListValue
)) {
HStack {
Text("TEAM")
Spacer()
if dataModel.team1ListValue.count == 0 {
Text("IS ANY").foregroundColor(Color("TPLightGrey"))
} else {
Text( self.dataModel.team1ListValue.joined(separator: ", ")).foregroundColor(Color("TPOrange"))
}
}
}
}
.listRowBackground(Color("TPDarkGrey"))
.font(.system(size: 14))
} // attention hear************
.navigationBarTitle("", displayMode: .inline)
.navigationBarHidden(true)
}
I couldn't compile your project, so I assume the following solution:
You can bind navigationBarHidden to variable, so that you can change the value under certain conditions. Like this: .navigationBarHidden($onOff)
struct ContentView: View {
#State var onOff = false
var body: some View {
NavigationView {
Button("Button") {
self.onOff.toggle()
}
.navigationBarTitle(Text("Events"), displayMode: .inline)
.navigationBarHidden($onOff.wrappedValue)
}
// that means only show one view at a time no matter what device I'm working
.navigationViewStyle(StackNavigationViewStyle())
}
}
Arrrgh... this was unnecessary: .navigationBarHidden(true) in MatchupView

SwiftUI NavigationLink Hide Arrow

Is there a way to hide the arrow to the right of the navigation link view that is automatically added?
I want to show an image grid using NavigationView -> List -> HStack -> NavigationLink_1 - NavigationLink_2
The NavigationLinks have arrows and it looks weird
The way it worked for me:
List {
ForEach(elements) { element in
ZStack {
CustomView(element: element)
NavigationLink(destination: DestinationView()) {
EmptyView()
}.buttonStyle(PlainButtonStyle())
}
}
}
The easiest way I've found is to place the navigation in the .background modifier with the opacity of zero:
List {
Text("The cell")
.background( NavigationLink("", destination: Text("The detail view")).opacity(0) )
}
And with this solution you don't loose the dynamic height functionality of the cells.
I got it done with this
NavigationLink(destination: DestinationView()) {
EmptyView()
}
.frame(width: 0, height: 0)
.hidden()
#State var selection: Int? = nil
var body: some View {
let navigation = NavigationLink(destination: Text("View"), tag: 1, selection: $selection) { EmptyView() }
return
VStack {
navigation
Text("Tap").onTapGesture { self.selection = 1 }
}
}
The only thing that helped me is to add .opacity(0) to NavigationLink like so:
List {
ForEach(elements) { element in
ZStack {
CustomView(element: element)
NavigationLink(destination: DestinationView()),
label: {}).opacity(0)
}
}
}
List {
ForEach(elements) { element in
ZStack {
CustomView(element: element)
NavigationLink(destination: DestinationView()) {
EmptyView()
}.opacity(0.0)
}
}
}
Setting .opacity(0) on the NavigationLink seems to be the most reliable solution for me because I noticed that it might show the indicators again when messing with the .listStyle property. You will also not lose the highlighted effect.
var body: some View {
NavigationView {
List {
ForEach(items) { item in
ZStack(alignment: .leading) {
NavigationLink(destination: EmptyView()) {
EmptyView()
}
.opacity(0)
Text(item.value)
}
}
}
}
}
This is what worked for me, just adding an empty NavigationLink in a ZStack
List(viewModel.items, id: \.id) { item in
ZStack {
NavigationLink(destination: Destination()) {}
CustomView(item: item)
}
}
Only this worked for me, when I tried to implement button tap inside row in List:
ZStack {
NavigationLink(destination: FlightBoardInformation(flight: flight), tag: FlightBoardNavigation.toFlightDetailed, selection: $navigation) {
EmptyView()
}
.frame(width: 0, height: 0)
.hidden()
.disabled(true)
Button(action: {
self.navigation = .toFlightDetailed
}) {
Text("\(self.flight.airline) \(self.flight.number)")
}.buttonStyle(PlainButtonStyle())
}
Although .background(...).opacity(0) works, in a more complex view it expands itself through all the view and conflicts with other elements like buttons.
If you need it inside a List, what worked for me is also marking the NavigationLink as .disabled(true):
Text(...)
.background( NavigationLink(...).opacity(0).disabled(true) )
Use .background modifier.
ForEach(elements) { e in
AnyViewYouWantToShow(e)
.background(
NavigationLink("", destination: DestinationView()))
.opacity(0)
)
}
Finally found out a way how to avoid the the chevron without doing some tricky ZStacks and other solutions. The only downside is that this is only tested on iOS 16 with the new NavigationPath + NavigationStack.
Instead of using a regular NavigationLink where you apply the hashable object, you'll just use a regular Button and append the object to the NavigationPath.
Example:
#State private var path = NavigationPath()
var body: some View {
List {
ForEach(viewModel.customers) { customer in
Button {
path.append(customer)
} label: {
CustomerCell(customer: customer)
}
}
}
.navigationDestination(for: Customer.self) { customer in
CustomerView(customer: customer)
}
}
For projects using the NavigationBackport (for preparing the new navigation), it might work as well. As you can use NBNavigationPath and append the object to the path with a Button just like the example above.
The best workaround for me is using background:
NavigationLink(...) {}
.opacity(0)
.background(
HStack {
Text("Your custom view without arrow")
}
)
Or if you need dynamic height as #turingtested posted use NavigationLink as background
Text("Your custom view without arrow")
.background(NavigationLink( ... ) {}.opacity(0))
though there is lots of solution. I'm posting my one.
var body: some View {
VStack{
List{
ForEach (items){item in
switch item.onClick {
//For SettingsOverviewView
case .Settings:
ZStack{
NavigationLink (destination: SettingsMenuView(item: item)){
EmptyView()
}
.opacity(0.0)
.buttonStyle(PlainButtonStyle())
//some views that you will show as your listItem
HStack {
Text(item.name)
.font(.body)
Spacer()
}
}
}
}
.listStyle(GroupedListStyle())
}
}
}
A lot of examples playing around with ZStack and .opacity but for my opinion SwiftUI can offer more elegant solution using NavigationLink with isActive parameter that works perfect with .listRowSeparator or .listStyle modificators:
struct HidingNavArrowInList: View {
let planets = ["Mars", "Sun", "Mercury", "Venus", "Jupiter", "Uranus", "Saturn", "Earth"]
#State var selectedPlanet: String?
#State var showDetailView = false
var body: some View {
NavigationView {
List {
ForEach(planets, id: \.self) { planet in
Text(planet)
.onTapGesture {
segue(planet: planet)
}
}
}
.background(
NavigationLink(isActive: $showDetailView, destination: {
if let unwrappedPlanet = selectedPlanet {
VStack {
Text("This is detail view of \(unwrappedPlanet)")
}
}
}, label: {
EmptyView()
})
)
}
}
private func segue(planet: String) {
selectedPlanet = planet
showDetailView.toggle()
}
}
I've also struggled with this recently and I think I've found a solution by using a custom view for the navigation link (it works for me):
struct CustomNavigationLink<D: View, L: View>: View {
#ViewBuilder var destination: () -> D
#ViewBuilder var label: () -> L
#State private var isActive = false
var body: some View {
Button {
withAnimation {
isActive = true
}
} label: {
label()
}
.onAppear {
isActive = false
}
.overlay {
NavigationLink(isActive: $isActive) {
destination()
} label: {
EmptyView()
}
.opacity(0)
}
}
}
And you use like this:
CustomNavigationLink {
SomeViewHere()
} label: {
Text("hello world")
}
2023 Update
This simple solution works for me:
ZStack {
CustomCell()
NavigationLink(destination: DetailView()) {
EmptyView()
}
.opacity(0)
}
You can also do like:
This worked for me,
#State var boolValue: Bool = false
HStack {
Text("Your text")
Toggle(isOn: $boolValue){
Text("")
}
if boolValue {
NavigationLink(destination: DestinationView()) {
EmptyView()
}.frame(width: 0)
}
}
It also works with any View (not only Text)
ZStack {
Text("Some text")
NavigationLink(destination: Text("Hello")) {
EmptyView()
}.frame(width: 0)
}
I set the opacity of the navigationLink to zero and it work like a charm
NavigationLink(
destination: Text("Destination"),
label: {}
).opacity(0)