ios - SwiftUI ScrollView 使用 .id() 滚动过去的元素
问题描述
有什么方法可以在ScrollView
滚动过去被赋予某个 ID 的元素时得到通知?
例如:
@State var selectedFoodTypeId: UUID? = nil
HStack {
ForEach(foodTypes) { foodType in
Text(foodType)
.foregroundColor(selectedFoodTypeId == foodType.id ? .red : .black)
}
}
ScrollView {
ForEach(foodTypesAndRestaurants) { item in
Text(item.foodType)
.id(item.foodType.id)
// When ScrollView was just scrolled here, I would like to do the following:
// withAnimation {
// selectedFoodTypeId = item.foodType.id
// }
ForEach(item.restaurants) { restaurant in
Text(restaurant)
}
}
}
解决方案
您可以使用其中一个.onAppear(perform: { })
或 .onDisappear(perform: {})
与其他逻辑一起使用。
Text(item.foodType)
.id(item.foodType.id)
.onAppear(perform: { })
推荐阅读
- python - 有没有办法阻止已经在执行的命令在 discord.py 中完成?
- c# - 与 SQL Server 中的几何列相交
- android - 在 Qt 中使用 tensorflow lite
- three.js - 为什么附加到组后顶点不更新?
- python - 如何使用 win32gui.ReleaseDC(,)
- excel - 具有动态字段列的 VBA 自动过滤器
- mongodb - mongodb选择所有非空或空字符串的字段
- css - 是否有一种全局 CSS / SCSS / 正则表达式方法可以仅使用不同的字体设置 NUMBERS 样式?
- math - 给出 Σ = {a, b} 的正则表达式
- php - WordPress“save_post”仅在保存帖子时调用,而不是在更新时调用