【问题标题】:How do you get rid of excess white space after a Form object in SwiftUI?在 SwiftUI 中,如何去除 Form 对象后多余的空白?
【发布时间】:2021-08-25 16:06:56
【问题描述】:

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

代码如下:

        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)
    

这是一个显示问题的图像:

【问题讨论】:

标签: ios swift xcode swiftui


【解决方案1】:

这个答案和我的答案here非常相似。

我的答案使用SwiftUI-Introspect,这样就可以得到内容高度,而不必猜测正确的高度。您可以确定这将适应各种因素,例如屏幕方向、字体大小等。

Form 的高度非常贪婪 - 你需要以某种方式限制它。我正在做的是获取Form 内容的真实高度,然后使用它来限制Form 高度。

解决方案

  1. 创建一个@State 变量来包含内容高度:
@State private var contentHeight: CGFloat?
  1. 添加代码限制Form高度:
Form {
    /* ... */
}
.introspectTableView { tableView in
    contentHeight = tableView.contentSize.height
}
.frame(height: contentHeight)

就是这样!

结果:

【讨论】:

    【解决方案2】:

    当您在代码中选择表单时,您会在画布中看到它占据了屏幕中所能获得的所有空间,因此将 TextField 和 Button 推到了屏幕的末尾。

    有两种可能的选择。第一个是您按原样使用 Picker,不要将其放入 Form 中。你会看到这些观点会融合在一起。第二种可能性是设置窗体的框架高度与您想要给它的高度,然后屏幕看起来更好。

    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])
                }
            }
        }
        .frame(height: 100, alignment: .center)
            
        TextField("Enter your question", text: $question)
            .opacity(selectedIndex > 0 ? 1 : 0)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    
        Button(action: {}) {
            Text("Ask")
        }
        .opacity(selectedIndex > 0 ? 1 : 0)
    }
    

    【讨论】:

    • 嗨,Aditya,当这是正确答案时,您能否将其标记为正确答案?谢谢。
    • 我不确定如何将其标记为正确答案,但这有效!谢谢!
    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2012-01-18
    相关资源
    最近更新 更多