【问题标题】:How to remove extra margin above a Form如何删除表格上方的额外边距
【发布时间】:2020-11-02 22:40:45
【问题描述】:

我希望部分视图包含在 Form 中,但不是全部。我不希望Form 占用那么多空间,所以我使用.frame() 缩小了它。虽然在 Form 上面还有很多余量。这是我的代码。

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                    Form {
                        Text("Some text in a form")
                    }
                        .frame(width: 400, height: 90) // shrinks Form size, but doesn't remove margin
         
                    Text("Some more text")
               }
            }
        }
    }
}

.frame() 的高度似乎并未移除表单顶部的多余空间(浅灰色区域)。

我也尝试将.listRowInsets(EdgeInsets()) 添加到第一个Text 视图中,但这不会删除上边距。有什么想法吗?

【问题讨论】:

  • 恐怕这是不可能的。您可以考虑开发完全自己的解决方案,而不是使用内置的表单。这样做的一个优点是它为您提供了所有灵活性,但缺点是它可能需要一些时间,并且您可能无法获得与 iOS 其余部分相同的外观。

标签: swift swiftui margin ui-design swiftui-form


【解决方案1】:

Form 没有隐藏标题的直接属性。为此,您需要使用下面的部分 -

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                     Form {
                        Section(header: VStack(alignment: .center, spacing: 0) {
                           Text("Some text in a form").foregroundColor(Color.black).padding(.all, 6)
                        }) {
                            EmptyView()
                        }
                     }
                     .frame(width: 400.0, height: 40.0)
         
                    Text("Some more text")
               }
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    该空白区域是大标题的导航视图栏空间(默认情况下),在您的情况下为空,因此只需隐藏它

        var body: some View {
            NavigationView {
                ScrollView {
                    VStack {
                        Form {
                            Text("Some text in a form")
                        }
                            .frame(width: 400, height: 90) // shrinks Form size, but doesn't remove margin
    
                        Text("Some more text")
                   }
                }
                .navigationBarTitle("")            // << this !!
                .navigationBarHidden(true)      // << and this !!
            }
        }
    

    【讨论】:

    • 这行不通。 @Evan93 想要删除的额外空间实际上是 Form 的标题,而不是导航栏。