简体   繁体   中英

SwiftUI app crashes when trying to expand/collapse sections on a sheet

The idea is that when user clicks on the headers,they expand revealing the controls.

It crashes when I expand one of the sections, then click in the TextField and then click on a different section to make the current one collapse and the other one to expand.

Things to note:

  1. This is only a problem with 'sheet'. If I present the DetailView via NavigationLink, it works perfectly
  2. It only happens if I click on the TextField. If I just expand/collapse sections - everything works
  3. Xcode 11.6, targeting and running on iOS 13.6

What is wrong with my code? Or is it a bug in SwiftUI?

I distilled the offending code into the smallest working example

struct DetailView: View {
    @State var name: String = "Default name"
    
    @State var location: String = "Default location"
    
    @State var expanded : Int = -1
    
    var body: some View {
        VStack {
            Button (action: {self.expanded = 0}) {
                HStack {
                    Text(self.name).font(.caption)
                    Spacer()
                    Image (systemName: "chevron.right")
                }
            }
            if self.expanded == 0 {
                TextField ("Enter name", text: self.$name)
            }
            
            Button (action: {self.expanded = 1}) {
                HStack {
                    Text(self.location).font(.caption)
                    Spacer()
                    Image (systemName: "chevron.right")
                }
            }
            if self.expanded == 1 {
                TextField ("Enter location", text: self.$location)
            }
            Spacer()
        }.padding()
    }
 }


 struct ContentView: View {
    @State var showDetail = false
    
    var body: some View {
        NavigationView {
            
            Button ("Detail") {
                self.showDetail = true
            }.sheet(isPresented: self.$showDetail, content: {DetailView()})
            
        }
    }
}

In case anyone lands here from google, it ended up being the same problem as here SwiftUI iOS app crashes when state change causes keyboard to resign as first responder while in a sheet

In my case however the stack was unhelpfully empty and only after countless attempts did I get one that had ViewRendererHost.render on top apart from generic 'main' event loop. Sure enough googling it immediately produced the above link

Reported this to Apple. It's clearly a bug in SwiftUI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM