1

我已经基于此链接构建了一个 Chips Container 。基本上只是一个成排订购芯片的容器。这是我的代码:

struct ChipsContent: View {
    @ObservedObject var viewModel = ChipsViewModel()
    @State private var totalHeight
              = CGFloat.zero
    
    var body: some View {
        var width = CGFloat.zero
        var height = CGFloat.zero
        return ScrollView {
            GeometryReader { geo in
                    ZStack(alignment: .topLeading, content: {
                    ForEach(viewModel.dataObject) { chipsData in
                        Chips(systemImage: chipsData.systemImage,
                              titleKey: chipsData.titleKey,
                              isSelected: chipsData.isSelected)
                            .padding(.all, 5)
                            .alignmentGuide(.leading) { dimension in
                                if (abs(width - dimension.width) > geo.size.width) {
                                    width = 0
                                    height -= dimension.height
                                }
                                
                                let result = width
                                if chipsData.id == viewModel.dataObject.last!.id {
                                    width = 0
                                } else {
                                    width -= dimension.width
                                }
                                return result
                              }
                            .alignmentGuide(.top) { dimension in
                                let result = height
                                if chipsData.id == viewModel.dataObject.last!.id {
                                    height = 0
                                }
                                return result
                            }
                    }
                    }).background(viewHeightReader($totalHeight))
            }.padding(.all, 5)
        }.frame(height: height)
    }
    
    private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
            return GeometryReader { geometry -> Color in
                let rect = geometry.frame(in: .local)
                DispatchQueue.main.async {
                    binding.wrappedValue = rect.size.height
                }
                return .clear
            }
        }
}

使用此代码,容器根据其内容获取高度。我想为滚动视图设置一个最大高度,如果内容大于这个最大高度,则内容应该是可滚动的。有可能这样做吗?

4

1 回答 1

2

使用 .frame(minHeight: ..., maxHeight: ...)

通过设置最小和最大高度,您限制了 SwiftUI 决定大小的自由度,因此您有更多的控制权而不是仅提及 .frame(height:...),它被视为建议,但不是一个值必须治疗。

于 2021-06-17T20:01:08.647 回答