【问题标题】:How to add blank space at the bottom of a form in SwiftUI?如何在 SwiftUI 中的表单底部添加空格?
【发布时间】:2020-06-05 01:07:26
【问题描述】:

我在 SwiftUI 中有一个用于添加记录的模式表。模式表使用具有多个 TextField 元素的表单。现在我想在表单末尾添加一些空间,与表单背景颜色相同(灰色)。

将 padding() 添加到最后一个 TextField 会导致所有 TextField 都具有填充。然后我尝试添加一个 Text("").hidden().padding(.bottom, 500) 作为最后一个表单元素,但是空间随后被白色背景色填充。

更新:如果您在表单视图中放置一个带有填充的间隔器,您会得到以下结果(背景为红色以进行演示):

这是代码:

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Hello, World!")
        }
        .sheet(isPresented: .constant(true), content: { SheetView() }
        )
    }
}

struct SheetView: View {
    var body: some View {
        Form {
            TextField("Demo Field", text: .constant("KK"))
            Spacer()
                .padding(.bottom, 500)
                .background(Color(.red))
        }
    }
}

我要查找的内容与 Apple 的“通讯录”应用中的内容相同。如果您转到“新联系人”并向下滚动到表单的末尾,则会有相当多的空间:

【问题讨论】:

  • 尝试添加 Spacer()
  • 不幸的是,这不起作用。请查看我的更新说明。
  • 我在下面发布了一个更好的解决方案以及您的更新说明。

标签: forms swiftui


【解决方案1】:

考虑像这样添加Spacer()

Spacer()
  .padding(.bottom, 500)
  .background(gray)

【讨论】:

  • 不幸的是,这也不起作用。如果将分隔符放在 Form 视图中,它只会创建另一个白行。如果你把它放在表单视图之外,它就不会再随着表单滚动了。
【解决方案2】:

为此,您必须使用section

struct SheetView: View {
    var body: some View {
        Form {
            Section(header: Text("")) {
                TextField("Demo Field", text: .constant("KK"))
            }
            Section(header: Text("")) {
                EmptyView()

            }
            .padding(.bottom, 200)
            Section(header: Text("")) {
                TextField("Demo Field", text: .constant("KK"))
            }
        }
    }
}

结果:

【讨论】:

  • 就是这样!您能否稍微编辑一下您的源代码,因为第二部分应该是空的并添加了填充。我已经使用了它并且它有效: Section(header: Text("")) {EmptyView() }.padding(.bottom, 200)
  • 请查看更新后的答案。这就是你想要的吗?
  • 是的,不需要第二个 TextField,但这没关系。谢谢!
  • 其实你不需要空头Text和EmptyView。所以你也可以写:Section {}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2014-03-09
  • 2011-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多