swiftUI PresentaionLink does not work second time

家住魔仙堡 提交于 2019-11-26 16:46:24

问题


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?


回答1:


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.

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)") })
    }
}


来源:https://stackoverflow.com/questions/57063633/swiftui-presentaionlink-does-not-work-second-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!