您可以使用并GeometryReader
设置 aminWidth
的内容。ScrollView
示例(出于测试目的将图像换成颜色):
struct ContentView: View {
@State private var width: CGFloat?
private let total = 10//0
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(0 ..< total) { index in
Color.red.opacity(Double(index) / Double(total) + 0.05)
.frame(width: 20)
}
// ForEach(images.indices, id: \.self) { index in
// let image = images[index] {
// Image(uiImage(uiImage: image))
// }
// }
}
.frame(height: 200)
.frame(minWidth: width)
}
.widthReader { width in
self.width = width
}
}
}
自定义widthReader(_:)
修饰符:
extension View {
func widthReader(_ width: @escaping (CGFloat?) -> Void) -> some View {
modifier(WidthReaderModifier(width: width))
}
}
fileprivate struct WidthReaderModifier: ViewModifier {
private struct WidthPreferenceKey: PreferenceKey {
static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
value = nextValue()
}
}
let width: (CGFloat?) -> Void
func body(content: Content) -> some View {
content
.background(
GeometryReader { geo in
Color.clear
.preference(key: WidthPreferenceKey.self, value: geo.size.width)
.onAppear {
width(geo.size.width)
}
}
)
.onPreferenceChange(WidthPreferenceKey.self) { width in
self.width(width)
}
}
}