ios - SwiftUI - 动态过滤时防止部分在列表中向右飞行/缩放
问题描述
我最初问了这个问题:
在那里,我有一个List
没有部分。我正在过滤它们,以便它只显示包含文本的行TextField
。解决方案是将所有内容包装List
在Section
.
不幸的是,我现在需要过滤Section
s。这是我的代码:
struct Group: Identifiable {
let id = UUID() /// required for the List
var groupName = ""
var people = [Person]()
}
struct Person: Identifiable {
let id = UUID() /// required for the List
var name = ""
}
struct ContentView: View {
@State var searchText = ""
var groups = [
Group(groupName: "A People", people: [
Person(name: "Alex"),
Person(name: "Ally"),
Person(name: "Allie")
]),
Group(groupName: "B People", people: [
Person(name: "Bob")
]),
Group(groupName: "T People", people: [
Person(name: "Tim"),
Person(name: "Timothy")
])
]
var body: some View {
VStack {
TextField("Search here", text: $searchText) /// text field
.padding()
List {
ForEach(
/// Filter the groups for those that contain searchText
groups.filter { group in
searchText.isEmpty || group.groupName.localizedStandardContains(searchText)
}
) { group in
Section(header: Text(group.groupName)) {
ForEach(group.people) { person in
Text(person.name)
}
}
}
}
.animation(.default) /// apply the animation
}
}
}
结果:
我在 中传入一个过滤数组ForEach
来确定Section
s。然而,每当这个数组改变时,List
动画真的很奇怪。Section
s 缩放/飞到右侧,当数组再次包含它们时从左侧返回。我怎样才能避免这个动画?
如果我删除.animation(.default)
,它根本不会像预期的那样设置动画。但是,我还是想要动画。有没有办法淡化更改,或者滑动它们?
解决方案
解决方案不使用列表。只要您不使用选择和行删除 ScrollView 基本上是相同的。
如果您想将其样式设置为有点像 List 也不是那么难:
struct SearchAnimationExample: View {
...
var body: some View {
VStack {
TextField("Search here", text: $searchText) /// text field
.padding()
ScrollView {
VStack(spacing: 0) {
ForEach(
groups.filter { group in
searchText.isEmpty || group.groupName.localizedStandardContains(searchText)
}
) { group in
Section(header: header(title: group.groupName)) {
ForEach(group.people) { person in
row(for: person)
Divider()
}
}
}.transition(.opacity) // Set which transition you would like
// Always full width
HStack { Spacer() }
}
}
.animation(.default)
}
}
func header(title: String) -> some View {
HStack {
Text(title).font(.headline)
Spacer()
}
.padding(.horizontal)
.background(Color.gray.opacity(0.4))
}
func row(for person: Person) -> some View {
HStack {
Text(person.name)
Spacer()
}.padding()
}
}
看起来与默认列表几乎相同:
推荐阅读
- mysql - 来自 MySQL 的大数据的推荐 ETL 解决方案?
- reactjs - 如何在反应中使用内联 if-else 条件语句显示状态值?
- sql - Microsoft Access 2016 SQL 未嵌套数组
- php - 如何检测坏人植入的 base64 编码字符串?
- python - Python FFmpeg 查询 rtsp 太慢
- macos - 如何让 jupyter notebook 识别 tensorflow?
- openshift - OpenShift:如何为用户分配密码?
- r - 指定 n 用于管道/ggplot/facet 网格中的百分比计算
- regex - Notepad++ 中的正则表达式:如果
- bash - 管道中的可执行文件 - 可执行文件是一次调用还是重复调用?