Swift开发:List滚动时顶部偏移问题修复咨询
解决SwiftUI List滚动顶部空隙问题
要解决List滚动时顶部可拖动产生空隙的问题,核心是关闭垂直方向的滚动弹性效果,同时保留正常的滚动功能,以下分版本给出解决方案:
iOS 16+ 解决方案
使用SwiftUI原生的scrollBounceBehavior修饰符,直接禁用垂直方向的弹性滚动:
// Display the list of the incorrect words List { ForEach(arrayToPass, id: \.self) { index in Text("・ \(displayeWord[index].word) : \(displayeWord[index].meaning1) ") .foregroundStyle(.black) .font(.title2) .padding(10) .bold() .listRowBackground(Color.white) } } .frame(width: 390, height: 400) .scrollContentBackground(.hidden) .scrollBounceBehavior(.disabled, axes: .vertical) // 禁用垂直方向弹性滚动
iOS 15及更低版本解决方案
由于scrollBounceBehavior是iOS16新增API,低版本需要通过UIKit的外观设置来修改List底层的UITableView属性:
// Display the list of the incorrect words List { ForEach(arrayToPass, id: \.self) { index in Text("・ \(displayeWord[index].word) : \(displayeWord[index].meaning1) ") .foregroundStyle(.black) .font(.title2) .padding(10) .bold() .listRowBackground(Color.white) } } .frame(width: 390, height: 400) .scrollContentBackground(.hidden) .onAppear { UITableView.appearance().bounces = false } .onDisappear { UITableView.appearance().bounces = true // 恢复全局设置,避免影响其他List }
额外提示
你的ForEach写法存在潜在风险:当前闭包参数index实际是arrayToPass的元素,而非数组索引。如果arrayToPass是存储displayeWord索引的数组,写法没问题;否则建议直接遍历目标数据元素,避免索引越界:
// 假设arrayToPass是筛选后的错误单词索引,直接遍历符合条件的索引 ForEach(displayeWord.indices.filter { arrayToPass.contains($0) }, id: \.self) { index in Text("・ \(displayeWord[index].word) : \(displayeWord[index].meaning1) ") // ... 其他修饰符 }
内容的提问来源于stack exchange,提问作者Iku
相关产品推荐
相关产品推荐

