SwiftUI:弹出窗口持续存在(在外部点击时不会被关闭)

Man*_*ero 5 popover swiftui

我创建了这个弹出窗口:

import SwiftUI

struct Popover : View {
  @State var showingPopover = false

  var body: some View {

    Button(action: {
      self.showingPopover = true
    }) {
      Image(systemName: "square.stack.3d.up")
    }
    .popover(isPresented: $showingPopover){

    Rectangle()

      .frame(width: 500, height: 500)

    }
  }
}

struct Popover_Previews: PreviewProvider {
    static var previews: some View {
        Popover()
        .colorScheme(.dark)
        .previewDevice("iPad Pro (12.9-inch) (3rd generation)")
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

默认行为是在外部点击后关闭。

问题:如何将弹出窗口设置为: - 坚持(在外部点击时不会被关闭)?- 活动时不遮挡屏幕?

Cry*_*thm 3

我对这个问题的解决方案并不涉及旋转你自己的类似的弹出窗口。只需将.interactiveDismissDisabled()修饰符应用于弹出窗口的父内容,如下例所示:

import SwiftUI

struct ContentView: View {
    @State private var presentingPopover = false
    @State private var count = 0
    
    var body: some View {
        VStack {
            Button {
                presentingPopover.toggle()
            } label: {
                Text("This view pops!")
            }.popover(isPresented: $presentingPopover) {
                Text("Surprise!")
                    .padding()
                    .interactiveDismissDisabled()
            }.buttonStyle(.borderedProminent)

            Text("Count: \(count)")
            Button {
                count += 1
            } label: {
                Text("Doesn't block other buttons too!")
            }.buttonStyle(.borderedProminent)
        }
        .padding()
    }
}
Run Code Online (Sandbox Code Playgroud)

在 iPadOS 16 (Xcode 14.1) 上测试,演示视频如下:

注意:虽然按钮看起来失去了焦点,但它们仍然可以交互,并且可能是一个错误,因为在 macOS 上运行时不存在这种行为。