SwiftUI:TabView中图片滚动时onChange事件未触发问题
TabView滚动图片无法触发onChange事件的解决办法
你在TabView中滚动图片时,绑定的currentIndex对应的onChange事件完全没触发,你的代码如下:
@State private var currentIndex = 0 TabView(selection: $currentIndex) { ForEach(model, id: \.self) { detail in Image(uiImage: detail.image) .resizable() .ignoresSafeArea() .frame(width: 100,height: 100,alignment: .center) .aspectRatio(contentMode: .fill) } } .onChange(of: currentIndex) { _ in print("*********") print(currentIndex) }
XCode版本:15.2
问题根源
TabView的selection绑定生效的前提是,每个子视图都必须设置对应的tag值。你只给TabView绑定了$currentIndex,但所有Image都没加tag,TabView没法识别当前滚动到了哪一项,自然不会更新currentIndex,onChange事件也就不会触发。
修复后的代码
@State private var currentIndex = 0 TabView(selection: $currentIndex) { // 遍历数据源的索引,方便直接绑定tag ForEach(model.indices, id: \.self) { index in let detail = model[index] Image(uiImage: detail.image) .resizable() .ignoresSafeArea() .frame(width: 100, height: 100, alignment: .center) .aspectRatio(contentMode: .fill) .tag(index) // 关键:给每个图片项绑定对应索引的tag } } .onChange(of: currentIndex) { _ in print("*********") print(currentIndex) }
额外说明
- 用
model.indices遍历索引比直接遍历元素更稳妥,避免因为元素自身的id(比如你用的.self)变化导致绑定失效 - Xcode 15.2里TabView的selection逻辑和之前版本一致,核心就是子视图必须有匹配的tag值才能和绑定的变量联动
内容的提问来源于stack exchange,提问作者Elangovan Eaaswaramurty
相关产品推荐
相关产品推荐

