【问题标题】:SwiftUI main list scrollable header view without sections?没有部分的 SwiftUI 主列表可滚动标题视图?
【发布时间】:2020-07-22 15:09:33
【问题描述】:

有没有办法在不带部分的列表标题中放置一个视图?表格视图通常有一个名为tableHeaderView 的属性,它是整个表格的标题,与节标题无关。

我正在尝试创建一个列表并能够像 tableHeaderView 一样从 UITableView 滚动它。

struct MyView: View {
    
    let myList: [String] = ["1", "2", "3"]
    
    var body: some View {
        VStack {
            MyHeader()
            List(myList, id: \.self) { element in
                Text(element)
            }
        }
    }
}

【问题讨论】:

    标签: ios swift swiftui swiftui-list


    【解决方案1】:

    感谢Asperi。这是我对表头的最终解决方案。

    struct MyHeader: View {
        var body: some View {
            Text("Header")
        }
    }
    
    struct DemoTableHeader: View {
        let myList: [String] = ["1", "2", "3"]
    
        var body: some View {
            List {
                MyHeader()
                ForEach(myList, id: \.self) { element in
                    Text(element)
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      这是一个可能的方法的简单演示,其他所有内容(如样式、大小、对齐方式、背景)都是可扩展和可配置的。

      使用 Xcode 11.4 / iOS 13.4 测试

      struct MyHeader: View {
          var body: some View {
              Text("Header")
                  .padding()
                  .frame(maxWidth: .infinity)
          }
      }
      
      struct DemoTableHeader: View {
          let myList: [String] = ["1", "2", "3"]
      
          let headerHeight = CGFloat(24)
      
          var body: some View {
              ZStack(alignment: .topLeading) {
                  MyHeader().zIndex(1)               // << header
                      .frame(height: headerHeight)
      
                  List {
                      Color.clear                    // << under-header placeholder
                          .frame(height: headerHeight)
      
                      ForEach(myList, id: \.self) { element in
                          Text(element)
                      }
                  }
              }
          }
      }
      

      【讨论】:

      • 不错!但我希望标题也能随着列表滚动?
      • 那我误会了你 - 只需删除占位符并将标题移动到 ForEach 上方的列表中。
      • Asperi,太棒了!那行得通。我根据您的评论在这里发布了我的答案:)
      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 2016-05-21
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多