SwiftUI:调整弹出窗口的大小以适合

时间:2019-10-01 06:41:20

标签: swift xcode popover swiftui

我有一个弹出窗口示例,其中一个按钮触发了一个弹出窗口。弹出窗口仅包含少量UI,在这种情况下为两个按钮,但是它仍然占用大量空间,而不是像我从UIKit习惯的那样将内容整齐地包裹在内容周围。如何使弹出窗口适合内容的大小?

iPad模拟器的屏幕截图和以下代码:

Screenshot of the button with the popover open

struct ContentView: View {

    @State private var showingPopupA = false

    var body: some View {
        HStack {
            Button(action: {
                self.showingPopupA.toggle()
            }, label: {
                Text("Button")
            }).popover(isPresented: self.$showingPopupA) {
                VStack {
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option A")
                    }
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option B")
                    }
                }.background(Color.red)
            }
        }
    }
}

来自macOS的屏幕截图: macOS screenshot built with Xcode 11.0

2 个答案:

答案 0 :(得分:1)

在macOS上,以下代码如下:

enter image description here

struct PopoverExample: View {

    @State private var showingPopupA:Bool = false 
    var body: some View {
        HStack {
            Button(action: {
                self.showingPopupA.toggle()
            }, label: {
                Text("Button")
            }).popover(isPresented: self.$showingPopupA) {
                VStack {
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option A")
                    }
                    Button(action: {
                        // Do something
                        self.showingPopupA = false
                    }) {
                        Text("Option B")
                    }
                }.background(Color.red)
            }
        }
        .frame( maxWidth: .infinity, maxHeight: .infinity)
    }
}

项目link

答案 1 :(得分:1)

这似乎已在iOS 13.4 / Xcode 11.4 Beta中修复。弹出窗口的大小将等于现在的内容。