SwiftUI: popup does not dismiss

亡梦爱人 提交于 2020-02-25 05:28:49

问题


In a Swift-UI List (iOS), showing some CoreData Elements, I want to show a popup for each listelement to change an Attribute of the CoreData Element.

In the code below, it is not possible to dismiss the popup.
If I remove the .id(UUID()) from the List, it works fine.

The .id(UUID()) is needed in my app, because I change the predicate "on the fly" and that's the only way I know, to avoid that SwiftUI tries to compare all List-elements of the old and the new result. This performance issue was discussed in Performance Issue with SwiftUI List

Any Ideas how to solve this?

import Foundation
import SwiftUI

struct ContentView: View {
  @FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>

  var body: some View {
    VStack
    { Button("Create Testdata"){createTestdata()}
      List(items, id: \.self)
      { item in
        Line(item: item)
      }.id(UUID())
    }
  }
}

struct Line: View {
  @ObservedObject var item : Item
  @State var showSheet = false

  var body: some View {
    Text(item.text!)
    .onLongPressGesture {
      self.showSheet.toggle()// = true
    }
    .popover( isPresented: self.$showSheet,
              arrowEdge: .trailing
            )
    { Pop(showSheet: self.$showSheet, item: self.item )
    }
  }
}

struct Pop: View {
  @Binding var showSheet: Bool
  var item : Item
    //@Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
           Text("CHANGE TO XXXXXXXXX")
            .onTapGesture
            { self.item.text = "XXXXXXX"
              self.showSheet = false
            }
            Text("CHANGE TO YYYYYYYYY")
            .onTapGesture
            { self.item.text = "YYYYYY"
              self.showSheet = false
            }
            Button("Cancel")
            {
                #if os(OSX)
                NSApp.sendAction(#selector(NSPopover.performClose(_:)), to: nil, from: nil)
                #else
                //self.presentationMode.wrappedValue.dismiss() // << behaves the same as below
                self.showSheet = false
                #endif
            }
        }
    }
}

来源:https://stackoverflow.com/questions/60152674/swiftui-popup-does-not-dismiss

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