SwiftUI 列表中的 contentInset

Luk*_*nik 8 swiftui swiftui-list

有没有办法contentInset在 SwiftUI 上进行设置List?我需要调整底部插图以使最后一个项目在底部按钮上方可见。

在此处输入图片说明

我目前的解决方案如下

Section(header: Color.clear.frame(height: 64)) { EmptyView() }

但我想知道有没有更好的方法?

小智 22

对于浮动按钮,您可以.safeAreaInset使用List. 该按钮将保持固定在底部,列表将滚动并为其提供适当的填充。

List {
    ForEach((0...20), id: \.self) { row in
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit")
    }
}
.listStyle(.inset)
.safeAreaInset(edge: .bottom) {
    Button {
        //Button Action
    } label: {
        Text("Button")
            .font(.title3)
            .bold()
            .foregroundColor(.white)
            .padding()
            .background(Color.red)
            .cornerRadius(16)
    }
}
Run Code Online (Sandbox Code Playgroud)

底部带有浮动按钮的列表插图


ege*_*eke 7

我对您的问题的解决方案看起来与Asperi的答案相似,但他的答案不会显示Button在视图的顶部,因为Button位于Form. (Button如果您不滚动到底部,将不可见。)


struct ContentView: View {
  
  @Environment(\.colorScheme) var colorScheme
  
  let stringArray: [String] = [String](repeating: "Example", count: 30)
  
  var body: some View {
    ZStack(alignment: .bottom) {
      List {
        ForEach(0..<stringArray.count) { stringIndex in
          Section {
            Text(stringArray[stringIndex])
          }
          
          if  stringIndex == stringArray.count - 1 {
            Spacer()
              .listRowInsets(EdgeInsets())
              .listRowBackground(
                colorScheme == .light ?
                  Color(.secondarySystemBackground) :
                  Color(.systemBackground)
              )
          }
        }
      }
      .listStyle(InsetGroupedListStyle())
      
      Button(action: {}) {
        Label("ADD NEW ITEM", systemImage: "plus")
      }
      .foregroundColor(.white)
      .font(.headline)
      .frame(height: 64)
      .frame(maxWidth: .infinity)
      .background(Color.red)
      .cornerRadius(5)
      .padding(.horizontal)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Asp*_*eri 2

可能的简单解决方案就是使用footer最后一节。

下面是一个独立的演示(当然您可以根据需要调整样式)。使用 Xcode 12.4 / iOS 14.4 进行测试

演示

struct DemoButtonInLastSection: View {
    let data = Array(repeating: "some", count: 20)

    var body: some View {
      Form {
        ForEach(data.indices, id: \.self) { i in
          Section(footer:
            Group {
                if i == data.count - 1 {
                    Button(action: {}) {
                        RoundedRectangle(cornerRadius: 8)
                            .overlay(
                              Label("ADD NEW ITEM", systemImage: "plus")
                               .foregroundColor(.white))
                    }
                    .font(.headline)
                    .frame(height: 64)
                    .frame(maxWidth: .infinity)
                }
            }

        ) {
            Text("Item \(i)")
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)