本文介绍了SwiftUI:调整弹出框的大小以适合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小弹出框示例,其中一个按钮会触发一个弹出框.弹出框只包含一点 UI,在这种情况下是两个按钮,但它仍然占用了大量空间,而不是像我习惯的 UIKit 那样整齐地环绕内容.如何使弹出框适合内容的大小?

I've got a little popover sample in which a button triggers a popover. The popover only contains a little bit of UI, two buttons in this case, but it still takes up a lot of space instead of wrapping neatly around the content like I'm used to from UIKit. How do I make the popover fit to the size of the content?

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

Screenshot from the iPad simulator and code below:

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 上,以下代码如下所示:

On macOS the code below will look like this:

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

这篇关于SwiftUI:调整弹出框的大小以适合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 00:08