首页 > 解决方案 > 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)
        }
    }
}

标签: iosswiftui

解决方案


您可以使用其中一个.onAppear(perform: { }) .onDisappear(perform: {})与其他逻辑一起使用。


Text(item.foodType)
  .id(item.foodType.id)
  .onAppear(perform: { })

推荐阅读