【问题标题】:SwiftUI: InsetGroupedListStyle List and full-width headerSwiftUI:InsetGroupedListStyle 列表和全角标题
【发布时间】:2021-07-14 07:04:38
【问题描述】:

如何在 iOS 上使用 List 和 InsetGroupedListStyle 制作全角标题? 一种方法是使用负填充(作为我代码中的示例),但这似乎不是使用固定值的最佳解决方案,因为它可能会在未来发生变化。

有没有更好的办法?

示例代码:

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            Section (header:
                        VStack {
                            Text("Header")
                                .foregroundColor(.white)
                        }
                        .frame( // This doesn't remove list's paddings
                              minWidth: 0,
                              maxWidth: .infinity,
                              minHeight: 0,
                              maxHeight: .infinity,
                              alignment: .topLeading
                            )
                        .background(Color.red)
//                      .padding(.horizontal, -16) // This works, but fixed value is not the best solution.
                        .textCase(nil)
                        .font(.body)
            ) {
            Text("Hello, world!")
                .padding()
            }
        }
        .listStyle(InsetGroupedListStyle())
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

【问题讨论】:

    标签: ios swift list swiftui


    【解决方案1】:

    您可以将标题的width 设置为屏幕的width,并且您需要的填充(x2)可以从宽度上减少。可以使用GeometryReader 来实现这一点。例如,

    // Geometry reader to get the width
    GeometryReader { reader in
        List {
            Section (header:
                VStack {
                    Text("Header")
                        .foregroundColor(.white)
                }
                // Setting the frame of the Header to the size of the screen
                // Reducing 20 from the width, giving a padding of 10 on each side
                .frame(width: reader.size.width - 20, height: 20, alignment: .leading)
                .background(Color.red)
                .textCase(nil)
                .font(.body)
                ) {
                    Text("Hello, world!")
                        .padding()
                }
            }
            .listStyle(InsetGroupedListStyle())
    }
    

    你可以在下面看到结果

    【讨论】:

    • 有效!谢谢 :) 就我而言,我根本不想有填充,所以这对我有用:.frame(width: reader.size.width, height: 20, alignment: .leading) 但很高兴你向我展示了这个选项。下次可能有用。谢谢!
    • 很高兴能帮上忙 ;)
    【解决方案2】:

    你可以试试这个:

    ...
    {
      Text("Hello, world!").padding()
    }.headerProminence(.increased)     // <--- here
    

    【讨论】:

    • 似乎是个好主意,但我遇到了错误。我认为它是iOS 15.0+。我现在用的是 14。
    • 哈哈,是的,我正在使用针对 ios 15 的 macos 12。也许 ios 14 中有类似的东西。
    • 感谢您的帮助。我会一点。也许有人有另一个想法。如果没有,我猜你的回答是正确的,我只需要等待 iOS 15 :)
    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2021-07-06
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多