我创建了一个简单的列表视图,借助于"SwiftUIIntrospect"库,它可以自动改变高度。
这个库:
pod 'SwiftUIIntrospect'
ListDynamicHeight 代码:
import SwiftUI
import SwiftUIIntrospect
struct ListDynamicHeight<Content>:View where Content:View {
@State private var listContentHeight:CGFloat = .zero
var minHeight:CGFloat = 1
@ViewBuilder var content:Content
var body: some View {
List {
content
}
.scrollView { scroll in
DispatchQueue.main.async {
listContentHeight = scroll.contentSize.height
}
}
.frame(minHeight: minHeight, idealHeight: listContentHeight)
}
}
private extension View {
func scrollView(_ scrollView: @escaping (UIScrollView) -> ()) -> some View {
introspect(.scrollView, on: .iOS(.v15, .v16, .v17)) { scroll in
scrollView(scroll)
}
}
}
#Preview {
ListDynamicHeight(minHeight: 10) {
Text("Hello")
}
}
还有一个我创建的动态TextView(如果你喜欢的话,可以带有占位符),它与列表完美配合。
struct TextView: View {
@FocusState private var isInFocus:Bool
@Binding var text: String
var placeholder = ""
var shouldShowPlaceholder:Bool { text.isEmpty && !isInFocus }
var body: some View {
ZStack(alignment: .topLeading) {
if shouldShowPlaceholder {
Text(placeholder)
.padding(.top, 10)
.padding(.leading, 6)
.onTapGesture {
isInFocus = true
}
}
TextEditor(text: $text)
.colorMultiply(shouldShowPlaceholder ? .clear : .white)
.focused($isInFocus)
}
}
}
把所有东西放在一起:
struct ListAndTextView:View {
@State private var text = ""
var placeholder:String = "Your Comment here..."
var body: some View {
ListDynamicHeight {
TextView(text: $text, placeholder: placeholder)
}
}
}
#Preview {
ListAndTextView()
}