SwiftUI列表分区头部上方出现额外空白(仅真机存在)
SwiftUI列表分区头部加载时出现真机特有空白问题
问题现象
在真机中打开DetailView时,列表分区头部上方会出现额外空白;开始滚动后空白自动消失,但每次视图重新加载时都会重现此问题。该问题仅在真机上出现,模拟器运行完全正常。
已尝试的无效排查操作
- 重启设备
- 移除
.navigationTitle与.navigationBarTitleDisplayMode配置
根因推测
在.onAppear()回调中修改绑定到分区头部的headerText状态,导致视图初始布局计算异常,从而引发空白。
临时解决方案
将.onAppear()替换为.task(),避免视图加载阶段的布局冲突:
struct DetailView: View { @State var item: Item @State private var headerText = "Header" var body: some View { List { Section(header: Text("\(headerText)")) { Text("Text") } HStack { Text("Red Text") }.listRowBackground(Color.red) // 替换.onAppear为.task }.task { headerText = "Change Header" } } }
相关代码补充
列表视图代码(默认新项目配置):
var body: some View { NavigationView { List { ForEach(items) { item in NavigationLink(destination: DetailView(item: item), label: { Text(item.timestamp!, formatter: itemFormatter) }) } .onDelete(perform: deleteItems) } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } Text("Select an item") } }
内容的提问来源于stack exchange,提问作者DelegateSmacker
相关产品推荐
相关产品推荐

