How to change NavigationView's destination in SwiftUI? - ios

The need is to go to View1 by default and when onLongPressGesture to View2. #State is used to make it. And the code is as following:
#State var showingView2 = false
if self.showingView2 {
NavigationLink(destination: View2())
{ Cell(name: View2.name)
.onLongPressGesture(minimumDuration: 1) {
self.showingView2 = true
}
}
} else {
NavigationLink(destination: View1())
{ Cell(name: View1.name)
.onLongPressGesture(minimumDuration: 1) {
self.showingView2 = true
}
}
}
For the simplicity, new button cannot be added in the UI. I know the code cannot run, but I do not know how to fix it.
Any suggestion will help me. Thanks!
=========================================
Updated
Thanks for #Asperi!
But in my project there is ForEach in NavigationView, in which case the answer does not work. The code is following:
import SwiftUI
struct ContentView: View {
#State private var isLongPressed = false
let lyrics = ["a", "b", "c"]
var body: some View {
NavigationView {
List() {
ForEach(0..<lyrics.count) { (index) in
NavigationLink(destination:
Group {
if self.isLongPressed { Destination2() }
else { Destination1() }
})
{ Text(self.lyrics[index]) }
.simultaneousGesture(LongPressGesture(minimumDuration: 1).onEnded { flag in
self.isLongPressed.toggle()
})
}
}
}
}
}
struct Destination1: View {
var body: some View {
Text("Destination1")
}
}
struct Destination2: View {
var body: some View {
Text("Destination2")
}
}
Then how to make it in this case? And I do not want to change the short tap or long tap's function, just short tap to View1 and long tap to View2. Thanks!

Here is a demo of possible approach. Tested with Xcode 11.4 / iOS 13.4
struct TestAlternateDestinations: View {
#State private var isLongPressed = false
var body: some View {
NavigationView {
NavigationLink(destination: Group {
if isLongPressed { Destination2() }
else { Destination1() }}) {
Text(self.isLongPressed ? "Link2" : "Link1")
}
.simultaneousGesture(LongPressGesture(minimumDuration: 1).onEnded { flag in
self.isLongPressed.toggle()
})
}
}
}
struct Destination1: View {
var body: some View {
Text("Destination1")
}
}
struct Destination2: View {
var body: some View {
Text("Destination2")
}
}

Here is the final answer based on #Asperi.
And there is still a little bug. If not add many space in the NavigationLink's name, the long tap only work when you tap on the "a" "b" "c". On other space of the NavigationLink out of the "a" "b" "c", all tap is short tap.
import SwiftUI
struct ContentView: View {
#State private var isLongPressed = false
#State var currentTag: Int?
let lyrics = ["a", "b", "c"]
var body: some View {
NavigationView {
List {
ForEach(0..<lyrics.count) { index in
VStack{
HStack(alignment: .top) {
NavigationLink(destination: Group
{ if self.isLongPressed { Destination2() } else { Destination1() } }, tag: index, selection: self.$currentTag
) {
// This is still a little bug. If not add many space, the long tap only work when you tap on the "a" "b" "c". On other space of the NavigationLink out of the "a" "b" "c", all tap is short tap.
Text(self.lyrics[index] + " ")
}
}
}.simultaneousGesture(LongPressGesture().onEnded { _ in
print("Got Long Press")
self.currentTag = index
self.isLongPressed = true
})
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
self.currentTag = index
self.isLongPressed = false
})
.onAppear(){
self.isLongPressed = false
}
}
}
}
}
}
struct Destination1: View {
var body: some View {
Text("Destination1")
}
}
struct Destination2: View {
var body: some View {
Text("Destination2")
}
}

Related

SwiftUI TabView - run code in subview after sequential taps

I am trying to implement the behavior in a TabView when the user taps the same tab multiple times, such as in the iOS AppStore app. First tap: switch to that view, second tap: pop to root, third tap: scroll to the top if needed.
The code below works fine for switching and didTap() is called for every tap.
import SwiftUI
enum Tab: String {
case one
case two
}
struct AppView: View {
#State private var activeTab = Tab.one
var body: some View {
TabView(selection: $activeTab.onChange(didTap)) {
One()
.tabItem {
Label("one", systemImage: "1.lane")
}
.tag(Tab.one)
Two()
.tabItem {
Label("two", systemImage: "2.lane")
}
.tag(Tab.two)
}
}
func didTap(to value: Tab) {
print(value) // this captures every tap
}
}
extension Binding {
func onChange(_ handler: #escaping (Value) -> Void) -> Binding<Value> {
Binding(
get: { self.wrappedValue },
set: { newValue in
self.wrappedValue = newValue
handler(newValue)
}
)
}
}
What I am struggling with, is how to tell either One or Two that it was tapped for a second or third time? (How to pop and scroll is not the issue).
I have seen this: TabView, tabItem: running code on selection or adding an onTapGesture but it doesn't explain how to run code in one of the views.
Any suggestions?
You can record additional taps (of same value) in an array. The array count gives you the number of taps on the same Tab.
EDIT: now with explicit subview struct.
struct ContentView: View {
#State private var activeTab = Tab.one
#State private var tapState: [Tab] = [Tab.one] // because .one is default
var body: some View {
TabView(selection: $activeTab.onChange(didTap)) {
SubView(title: "One", tapCount: tapState.count)
.tabItem {
Label("one", systemImage: "1.lane")
}
.tag(Tab.one)
SubView(title: "Two", tapCount: tapState.count)
.tabItem {
Label("two", systemImage: "2.lane")
}
.tag(Tab.two)
}
}
func didTap(to value: Tab) {
print(value) // this captures every tap
if tapState.last == value {
tapState.append(value) // apped next tap if same value
print("tapped \(tapState.count) times")
} else {
tapState = [value] // reset tap state to new tab selection
}
}
}
struct SubView: View {
let title: String
let tapCount: Int
var body: some View {
VStack {
Text("Subview \(title)").font(.title)
Text("tapped \(tapCount) times")
}
}
}
Although the answer by #ChrisR did answer my question, I couldn't figure out the next step, i.e. the logic when to pop-to-root or scroll-to-the-top based on the number of taps for a SubView. After lots of reading and trial and error, I recently came across this article: https://notificare.com/blog/2022/11/25/a-better-tabview-in-swiftui/
Inspired by this article, but with some modifications, I came up with the following which does exactly what I was looking for.
The two main changes are:
An EmptyView with an id is added as the first (but invisible) row in the List to be used as an anchor by proxy.scrollTo().
Instead of the global #StateObject var appState that stores the navigation paths for the subviews, I added the paths as separate #State properties. This avoids the Update NavigationAuthority bound path tried to update multiple times per frame. warning.
Hopefully this is helpful for someone.
enum Tab: String {
case one
case two
}
struct ContentView: View {
#State var selectedTab = Tab.one
#State var oneNavigationPath = NavigationPath()
#State var twoNavigationPath = NavigationPath()
var body: some View {
ScrollViewReader { proxy in
TabView(selection: tabViewSelectionBinding(proxy: proxy)) {
SubView(title: "One", path: $oneNavigationPath)
.tabItem {
Label("one", systemImage: "1.lane")
}
.tag(Tab.one)
SubView(title: "Two", path: $twoNavigationPath)
.tabItem {
Label("two", systemImage: "2.lane")
}
.tag(Tab.two)
}
}
}
private func tabViewSelectionBinding(proxy: ScrollViewProxy) -> Binding<Tab> {
Binding<Tab>(
get: { selectedTab },
set: { newValue in
if selectedTab == newValue {
switch selectedTab {
case .one:
if oneNavigationPath.isEmpty {
withAnimation {
proxy.scrollTo(Tab.one, anchor: .bottom)
}
} else {
withAnimation {
oneNavigationPath = NavigationPath()
}
}
case .two:
if twoNavigationPath.isEmpty {
withAnimation {
proxy.scrollTo(Tab.two, anchor: .bottom)
}
} else {
withAnimation {
twoNavigationPath = NavigationPath()
}
}
}
}
selectedTab = newValue
}
)
}
}
struct SubView: View {
let title: String
let items = Array(1 ... 100)
#Binding var path: NavigationPath
var body: some View {
NavigationStack(path: $path) {
List {
EmptyView()
.id(Tab(rawValue: title.lowercased()))
ForEach(items, id: \.self) { item in
NavigationLink(value: item) {
Text("Item \(item)")
}
}
}
.navigationTitle(title)
.navigationDestination(for: Int.self) { item in
Text("Item \(item)")
}
}
}
}

swiftui subview reappear after click the back button and update state data

Very strange behavior.
Click the back button on the subpage (Subview) to return to the main page (ContentView). However, the subpage (Subview) automatically opens again. Why?
import SwiftUI
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
var body: some View {
NavigationView{
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
}
.onAppear {
update()
}
.navigationTitle("a")
.toolbar{
NavigationLink(destination: Subview(count: $count), label: {
Text("sub")
})
}
}
}
func update() {
things = []
for i in 0...count {
things.append(String(i))
}
}
}
struct Subview: View {
var count : Binding<Int>
var body: some View {
Text("sub")
.onAppear {
count.wrappedValue += 1
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
NavigationLink should always be inside a NavigationView. If you put it in the toolbar or some other place, you might run into weird issues.
Instead, use the init(destination:isActive:label:) initializer. Then set the presentingNextPage property to true when you want to present the next page.
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
#State var presentingNextPage = false
var body: some View {
NavigationView {
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
/// placeholder navigation link
NavigationLink(destination: Subview(count: $count), isActive: $presentingNextPage) {
EmptyView()
}
}
.onAppear {
self.update()
}
.navigationTitle("a")
.toolbar{
ToolbarItem(placement: .navigationBarTrailing) {
Button("sub") {
presentingNextPage = true /// set to true
}
}
}
}
}
func update() {
things = []
for i in 0...count {
things.append(String(i))
}
}
}
Result:
Put "onAppear{...}" on the NavigationView not the List, like this:
struct ContentView: View {
#State var things: [String] = []
#State var count: Int = 0
var body: some View {
NavigationView{
List {
ForEach(things.indices, id: \.self) { index in
Text(things[index])
}
}
.navigationTitle("a")
.toolbar{
NavigationLink(destination: Subview(count: $count), label: {
Text("sub")
})
}
}
.onAppear { // <---
update()
}
}

Attaching .popover to a ForEach or Section within a List creates multiple popovers

I have a List with multiple Section and each Section has different type of data. For each section I want clicking on an item to present a popover.
Problem is that if I attach the .popover to the Section or ForEach then the .popover seems to be applied to every entry in the list. So the popover gets created for each item even when just one is clicked.
Example code is below. I cannot attach the .popover to the List because, in my case, there are 2 different styles of .popover and each view can only have a single .popover attached to it.
struct Item: Identifiable {
var id = UUID()
var title: String
}
var items: [Item] = [
Item(title: "Item 1"),
Item(title: "Item 2"),
Item(title: "Item 3"),
]
struct PopoverView: View {
#State var item: Item
var body: some View {
print("new PopoverView")
return Text("View for \(item.title)")
}
}
struct ContentView: View {
#State var currentItem: Item?
var body: some View {
List {
Section(header: Text("Items")) {
ForEach(items) { item in
Button(action: { currentItem = item }) {
Text("\(item.title)")
}
}
}
}
}
}
The current best solution I have come up with is to attach the popover to each Button and then only allow one popover based on currentItem,
Button(action: { currentItem = item }) {
Text("\(item.title)")
}
.popover(isPresented: .init(get: { currentItem == item },
set: { $0 ? (currentItem = item) : (currentItem = nil) })) {
PopoverView(item: item)
}
Any better way to do this?
Bonus points to solve this: When I used my hack, the drag down motion seems to glitch and the view appears from the top again. Not sure what the deal with that is.
You can always create a separate view for your item.
struct MyGreatItemView: View {
#State var isPresented = false
var item: Item
var body: some View {
Button(action: { isPresented = true }) {
Text("\(item.title)")
}
.popover(isPresented: $isPresented) {
PopoverView(item: item)
}
}
}
And implement it to ContentView:
struct ContentView: View {
var body: some View {
List {
Section(header: Text("Items")) {
ForEach(items) { item in
MyGreatItemView(item: item)
}
}
}
}
}
Trying to reach component like sheet or popover in ForEach causes problems.
I've also faced the glitch you mentioned, but below (with sheet) works as expected;
List {
Section(header: Text("Items")) {
ForEach(items) { item in
Button(action: { currentItem = item }) {
Text("\(item.title)")
}
}
}
}
.sheet(item: $currentItem, content: PopoverView.init)
Here's a late suggestion, I used a ViewModifier to hold the show Popover state on each view, the modifier also builds the Popover menu and also handles the presented sheet initiated from the popover menu. (Here's some code...)
struct Item: Identifiable {
var id = UUID()
var title: String
}
var items: [Item] = [
Item(title: "Item 1"),
Item(title: "Item 2"),
Item(title: "Item 3"),
]
struct ContentView: View {
var body: some View {
List {
Section(header: Text("Items")) {
ForEach(items) { item in
Text("\(item.title)").popoverWithSheet(item: item)
}
}
}
}
}
struct SheetFromPopover: View {
#State var item: Item
var body: some View {
print("new Sheet from Popover")
return Text("Sheet for \(item.title)")
}
}
struct PopoverModifierForView : ViewModifier {
#State var showSheet : Bool = false
#State var showPopover : Bool = false
var item : Item
var tap: some Gesture {
TapGesture(count: 1)
.onEnded { _ in self.showPopover = true }
}
func body(content: Content) -> some View {
content
.popover(isPresented: $showPopover,
attachmentAnchor: .point(.bottom),
arrowEdge: .bottom) {
self.createPopover()
}
.sheet(isPresented: self.$showSheet) {
SheetFromPopover(item: item)
}
.gesture(tap)
}
func createPopover() -> some View {
VStack {
Button(action: {
self.showPopover = false
self.showSheet = true
}) {
Text("Show Sheet...")
}.padding()
Button(action: {
print("Something Else..")
}) {
Text("Something Else")
}.padding()
}
}
}
extension View {
func popoverWithSheet(item: Item) -> some View {
modifier(PopoverModifierForView(item: item))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

How to make NavigationLink work if it is not visible, SwiftUI?

When using NavigationLink on the bottom of a view after ForEach it won't work if it is not visible.
I have a list of Buttons. If a button is pressed, it sets a Bool to true. This bool value now shows a NavigationLink which immediately activates because the passed binding is set to true.
However, the link won't work if the array is too long because it will be out of sight once one of the first buttons is pressed.
This is my Code:
import SwiftUI
struct TestLinkView: View {
#State private var linkIsActive = false
var body: some View {
NavigationView {
VStack {
Button(action: {
linkIsActive = true
}) {
Text("Press")
}
NavigationLink(destination: ListView(linkIsActive: $linkIsActive), isActive: $linkIsActive) {
Text("Navigation Link")
}
}
}
}
}
struct ListView: View {
var nameArray = ["Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Name14","Name15","Name16","Name17","Name18","Name19","Name20" ]
#State private var showLink: Bool = false
#State private var selectedName: String = ""
#Binding var linkIsActive: Bool
var body: some View {
Form {
ForEach(nameArray, id: \.self) { name in
Button(action: {
selectedName = name
showLink = true
}) {
Text(name)
}
}
if showLink {
NavigationLink(destination: NameView(selectedName: selectedName), isActive: $linkIsActive) {
EmptyView()
}
}
}
.navigationBarTitle("ListView")
}
}
struct NameView: View {
var selectedName: String
var body: some View {
Text(selectedName)
.navigationBarTitle("NameView")
}
}
What would work is to pass the NavigationLink with the if-condition inside the button label. However if I do that, the animation won't work anymore.
You don't need it in Form, which is like a List don't create views far outside of visible area. In your case the solution is to just move link into background of Form (because it does not depend on form internals).
The following tested as worked with Xcode 12 / iOS 14.
Form {
ForEach(nameArray, id: \.self) { name in
Button(action: {
selectedName = name
showLink = true
}) {
Text(name)
}
}
}
.background(Group{
if showLink {
NavigationLink(destination: NameView(selectedName: selectedName), isActive: $linkIsActive) {
EmptyView()
}
}
})

Long press of NavigationView only work on the left part, not all the NavigationLink?

Following is a NavigationView, the view pops to Destination2 when long press the NavigationLink and to Destination1 when normally tap it. But the right zone of the NavigationLink in the picture cannot be long pressed.
Does anyone know the reason? Thanks!
import SwiftUI
struct ContentView: View {
#State private var isLongPressed = false
#State var currentTag: Int?
let lyrics = ["OutNotWorkA", "OutNotWorkB", "OutNotWorkC"]
var body: some View {
NavigationView {
List {
ForEach(0..<lyrics.count) { index in
VStack{
HStack(alignment: .top) {
NavigationLink(destination: Group
{ if self.isLongPressed { Destination2() } else { Destination1() } }, tag: index, selection: self.$currentTag
) {
Text(self.lyrics[index])
}
}
}.simultaneousGesture(LongPressGesture().onEnded { _ in
print("Got Long Press")
self.currentTag = index
self.isLongPressed = true
})
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
self.currentTag = index
self.isLongPressed = false
})
.onAppear(){
self.isLongPressed = false
}
}
}
}
}
}
struct Destination1: View {
var body: some View {
Text("Destination1")
}
}
struct Destination2: View {
var body: some View {
Text("Destination2")
}
}
Then how to handle the whole part?
Find below the fix
VStack{
HStack(alignment: .top) {
NavigationLink(destination: Group
{ if self.isLongPressed { Destination2() } else { Destination1() } }, tag: index, selection: self.$currentTag
) {
Text(self.lyrics[index])
}
}
}
.contentShape(Rectangle()) // << here !!
.simultaneousGesture(LongPressGesture().onEnded { _ in
LongPressGesture only works on the visualized part of the label.
The easiest way to handle this problem is a little workaround with a lot of spaces:
Text(self.lyrics[index]+" ")
Because only using spaces doesn't create a line break this makes no visual problems in your App.

Resources