解决一个问题,默认情况下ScrollView没有根据内容自适应高度。
查了stackoverflow,其中一个思路是,使用GeometryReader计算大小并使用。 经过简单封装处理,可以用如下方案解决:
swift
import Foundation
import SwiftUI
struct ScrollAutoShrink<Content: View>: View {
@ViewBuilder let content: () -> Content
@State private var scrollViewContentSize: CGSize = .zero
var body: some View {
ScrollView {
content()
.readSize($scrollViewContentSize)
}.frame(
maxHeight: scrollViewContentSize.height
)
}
}
struct SizeReaderModifier: ViewModifier {
@Binding var size: CGSize
func body(content: Content) -> some View {
content.background(
GeometryReader { geometry in
Color.clear.onAppear {
DispatchQueue.main.async {
size = geometry.size
}
}
}
)
}
}
extension View {
func readSize(_ size: Binding<CGSize>) -> some View {
modifier(SizeReaderModifier(size: size))
}
}
import Foundation
import SwiftUI
struct ScrollAutoShrink<Content: View>: View {
@ViewBuilder let content: () -> Content
@State private var scrollViewContentSize: CGSize = .zero
var body: some View {
ScrollView {
content()
.readSize($scrollViewContentSize)
}.frame(
maxHeight: scrollViewContentSize.height
)
}
}
struct SizeReaderModifier: ViewModifier {
@Binding var size: CGSize
func body(content: Content) -> some View {
content.background(
GeometryReader { geometry in
Color.clear.onAppear {
DispatchQueue.main.async {
size = geometry.size
}
}
}
)
}
}
extension View {
func readSize(_ size: Binding<CGSize>) -> some View {
modifier(SizeReaderModifier(size: size))
}
}
使用方法: 用ScrollAutoShrink
代替ScrollView
。
参考:ScrollView shrink to fit | Apple Developer Forums
How do I make a SwiftUI Scroll view shrink-to-content? - Stack Overflow