【问题标题】:Programaticly dismiss popover in SwifUI以编程方式关闭 SwiftUI 中的弹出框
【发布时间】:2020-05-24 17:36:25
【问题描述】:

我尝试通过设置变量来关闭弹出框,将其显示为 false。

示例代码的行为很奇怪。 有没有更好的方法可以使用取消按钮以编程方式关闭弹出框?

import SwiftUI

struct ContentView: View {
  let lines = ["line 1", "line 2","line 3"]
  var body: some View {
    List {
      ForEach(lines, id: \.self)
      { Line(text: $0)
      }
    }
  }
}

struct Line: View {
  @State var text: String
  @State var showSheet = false

  var body: some View {
    VStack
    { Text("\(text)")
      .onTapGesture {
        self.showSheet = true
      }
    }.popover( isPresented: self.$showSheet,
               arrowEdge: .trailing
             )
    { Pop(showSheet: self.$showSheet)
    }
  }
}

struct Pop: View {
  @Binding var showSheet: Bool

  var body: some View {
    VStack {   
      Text("Option 1")
      Text("Option 2")
      Button("Cancel")
      { self.showSheet = false
      }
    }
  }
}

【问题讨论】:

  • 我在 iPhone 11 模拟器中运行 Xcode 版本 11.3.1 (11C504) 中的示例代码。不可能多次点击和关闭。在设备上运行良好 - 可能是模拟器问题

标签: macos swiftui popover nspopover


【解决方案1】:

不清楚在哪个环境中以及究竟发生了什么奇怪,因为经过测试,提供的代码在 Xcode 11.2/3+ 和 iOS13.2+ 上运行良好。

无论如何,使用\.presentationMode 关闭弹出窗口的替代方法如下

更新:好吧,我发现原来的问题可能与 macOS 有关,因为在 macOS 弹出框上提供的内容并未在描述的情况下关闭。

这里是两个 iOS/macOS 平台的使用变体(经过测试并适用于 Xcode 11.3 / macOS 10.15)

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

    var body: some View {
        VStack {
            Text("Option 1")
            Text("Option 2")
            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
            }
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2012-10-09
  • 2017-10-14
相关资源
最近更新 更多