admin管理员组

文章数量:1421730

In an app of mine I have a text field and a button to show a definition of the inserted word provided by the system dictionaries. The problem is that, sometimes, when the sheet containing the UIReferenceLibraryViewController view appears it immediately disappears: the sheet opens fully, then immediately starts to go away. What bugs me is that this behaviour only happens some of the times, and I'd like to know if you have any idea why.

Example

Here's a minimum reproducible example I created which showcases the same problem.

ContentView

import SwiftUI

struct ContentView: View {
    @State private var term = ""
    
    var body: some View {
        VStack {
            TextField("Enter a term", text: $term)
                .padding()
            
            ShowDictionaryButton(term: term)
        }
    }
}

ShowDictionaryButton

import SwiftUI

struct ShowDictionaryButton: View {
    let term: String
    @State private var showingDictionary = false
    
    var body: some View {
        Button("Show dictionary") {
            showingDictionary = true
        }
        .sheet(isPresented: $showingDictionary) {
            DictionaryView(term: term)
                .ignoresSafeArea()
        }
    }
}

DictionaryView

import SwiftUI

struct DictionaryView: UIViewControllerRepresentable {
    let term: String
    
    typealias UIViewControllerType = UIReferenceLibraryViewController
    
    func makeUIViewController(context: Context) -> UIReferenceLibraryViewController {
        print("Making the DictionaryView")
        return UIReferenceLibraryViewController(term: term)
    }
    
    func updateUIViewController(_ uiViewController: UIReferenceLibraryViewController, context: Context) {
        print("Updating the DictionaryView")
    }
}

How to reproduce the error

Type a word in the text field and tap the button. You will notice that, sometimes, the sheet immediately closes. If this doesn't happen, manually close the sheet, then try and tap the button a few times or change the word and try again. I haven't figured it out when this happens, it seems completely random. Happens more often when trying for the first time, at least on my device.

本文标签: iosUIReferenceLibraryViewController instantly closes in SwiftUIStack Overflow