Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swiftUI PresentaionLink does not work second time

I have a ContentView written in swiftUI as simple as below.

var body: some View {
    
    NavigationView {
        List {
            Section {
                PresentationLink(destination: Text("new Profile")) {
                    Text("new Profile")
                }
            }
        }
    }

everything is good first time I tap on new profile but when I close the modal and try to tap again, it does not work.

is it a bug or a feature?

like image 480
Arash Avatar asked Jul 16 '19 18:07

Arash


1 Answers

PresentationLink has been deprecated in Xcode 11 beta 4 in favor of .sheet, which seems to solve the issue.

Added improved presentation modifiers: sheet(isPresented:onDismiss:content:), actionSheet(isPresented:content:), and alert(isPresented:content:) — along with isPresented in the environment — replace the existing presentation(_:), Sheet, Modal, and PresentationLink types. (52075730)

If you change the code to .sheet like below:

import SwiftUI

struct Testing : View {
    @State var isPresented = false

    var body: some View {
        NavigationView {
            List {
                Button(action: { self.isPresented.toggle() })
                    { Text("Source View") }
                }
            }.sheet(isPresented: $isPresented, content: { Text("Destination View") })
    }
}

You will then be able to use the modal as many times as you like instead of just once.

GIF showing that the modal can be brought up and dismissed several times instead of just once

EDIT: After implementing this in a real scenario, I've found that the underlying bug still seems to exist if you put .sheet inside of the List. If you follow the code example above, you won't experience this issue but in a real scenario where you're using a List, you're probably going to want information about the particular item that was selected passed in to the modal. In that case, you're going to need to pass information about the selection via a @State var or some other means. Below is an example:

import SwiftUI

struct Testing : View {
    @State var isPresented = false
    @State var whichPresented = -1

    var body: some View {
        NavigationView {
            List {
                ForEach(0 ..< 10) { i in
                    Button(action: {
                            self.whichPresented = i
                            self.isPresented.toggle()
                })
                        { Text("Button \(i)") }
                    }
                }
            }.sheet(isPresented: $isPresented, content: { Text("Destination View \(self.whichPresented)") })
    }
}
like image 138
Zain Avatar answered Oct 29 '22 19:10

Zain