SwiftUI 中的 Form 对象后,如何去除多余的空白? [英] How do you get rid of excess white space after a Form object in SwiftUI?

查看:38
本文介绍了SwiftUI 中的 Form 对象后,如何去除多余的空白?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的页面,其中有一个选项可以从几个不同的选项中进行选择,然后在选择一个选项后显示一个文本字段和按钮.逻辑运行良好,但不幸的是,在 Form 对象和其余 UI 元素之间存在大量空白 - 有没有办法改变这种情况?

代码如下:

 VStack {Text(你需要什么帮助?").font(.largeTitle).fontWeight(.bold).multilineTextAlignment(.center)形式 {选择器(颜色",选择:$selectedIndex){ForEach(0 ..< arrayOfNames.count) {文本(self.arrayOfNames[$0])}}}TextField("请输入您的问题", text: $question).opacity(selectedIndex > 0 ? 1 : 0).textFieldStyle(RoundedBorderTextFieldStyle())按钮(动作:{}){文本(询问")}.opacity(selectedIndex > 0 ? 1 : 0)

这是显示问题的图像:

解决方案

这个答案与我的答案非常相似

I'm trying to create a simple page that has an option to select from a few different options, and then a text field and button that show up after an option has been selected. The logic works great, but unfortunately there's a great deal of white space between the Form object and the rest of the UI elements - is there a way to change this?

Here is the code:

        VStack {
        Text("What would you like help with?")
            .font(.largeTitle)
            .fontWeight(.bold)
            .multilineTextAlignment(.center)
                    
        Form {
            Picker("Color", selection: $selectedIndex) {
                ForEach(0 ..< arrayOfNames.count) {
                    Text(self.arrayOfNames[$0])
                }
            }
        }
        
        TextField("Enter your question", text: $question)
            .opacity(selectedIndex > 0 ? 1 : 0)
            .textFieldStyle(RoundedBorderTextFieldStyle())
        
        Button(action: {}) {
            Text("Ask")
        }.opacity(selectedIndex > 0 ? 1 : 0)
    

And here is an image which shows the problem:

解决方案

This answer is very similar to my answer here.

My answer uses SwiftUI-Introspect, so you can get the content height and don't have to guess the correct height. You can be sure this will adapt to various things like screen orientation, font size, etc.

Form is very greedy in height - you need to limit it in some way. What I'm doing is getting the Form content's real height, and then using that to restrict the Form height.

Solution

  1. Create a @State variable to contain the content height:

@State private var contentHeight: CGFloat?

  1. Add code to restrict Form height:

Form {
    /* ... */
}
.introspectTableView { tableView in
    contentHeight = tableView.contentSize.height
}
.frame(height: contentHeight)

And that's it!

Result:

这篇关于SwiftUI 中的 Form 对象后,如何去除多余的空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆