iOS 15下SwiftUI ListStyle样式异常问题咨询
问题根因
iOS 15 对PlainListStyle的列表渲染逻辑做了改动:列表内容未填满Frame的空白区域默认改为透明,这是和iOS 14版本的核心差异,你遇到的表现属于系统版本的兼容问题。
修复方案
你可以保留PlainListStyle的紧凑边距,仅手动指定列表的背景色即可实现和GroupedListStyle一致的空白区域底色效果,兼容iOS 14+版本的代码修改如下:
import SwiftUI struct ContentView: View { // let arrayOfStuff = ["Horse","Cow","Screwdriver","Blender","Pyramid","Scotch Tape","Baseball card","CD","Checkbook","Fountain pen","Pin cushion","Couch","Potatos","Protractor"] let arrayOfStuff = ["Horse","Cow","Screwdriver","Blender"] @State var currentlySelectedItem = "" var body: some View { ZStack { Color(.red) .ignoresSafeArea() List { ForEach(arrayOfStuff, id: \.self){ item in Text(item) .onTapGesture { currentlySelectedItem = item } .listRowBackground(currentlySelectedItem == item ? Color.gray : Color(UIColor.systemGroupedBackground)) } } .listStyle(PlainListStyle()) .frame(width: 500, height: 500, alignment: .leading) // 新增修改开始 .background(Color(UIColor.systemGroupedBackground)) .onAppear { // 消除UITableView默认的背景色干扰 UITableView.appearance().backgroundColor = .clear } // 可选:如果其他页面不需要该配置,在页面消失时重置 .onDisappear { UITableView.appearance().backgroundColor = UIColor.systemGroupedBackground } // 新增修改结束 } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
如果你的项目最低支持iOS 16+,可以用更简洁的系统原生API实现,不需要修改全局UITableView外观:
List { // 原有列表内容不变 } .listStyle(PlainListStyle()) .frame(width: 500, height: 500, alignment: .leading) .scrollContentBackground(.hidden) .background(Color(UIColor.systemGroupedBackground))
内容的提问来源于stack exchange,提问作者Ben Long
相关产品推荐
相关产品推荐

