SwiftUI List无法撑满全屏宽度、背景色不生效且周围出现灰色边框问题
解决方案
你之前的配置不生效的核心原因是frame修饰符加在了ForEach容器上,没有作用到每个独立的列表行,同时没有移除List默认的inset分组样式带来的边距,按以下步骤修改即可:
- 给List添加
.listStyle(.plain)修饰符,移除iOS默认给分组列表添加的左右内边距和灰色分隔边样式 - 移除你当前加在ForEach末尾的frame修饰符,改为给每个列表行的内容容器添加三个修饰符:
.frame(maxWidth: .infinity, alignment: .leading)让行内容撑满可用宽度.listRowInsets(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0))把系统默认的列表行左右内边距设为0,上下数值可根据你需要的行间距自由调整.listRowBackground(Color.white)把行背景设为纯白色,覆盖默认的灰色背景
修改后的List部分代码参考:
List { ForEach(subjectVM.classData){ data in VStack(alignment: .leading,spacing: 10){ HStack { Text("\(String(format: "%.1f", data.rating)) \(data.key)") .font(.body) .font(.system(size: 12)) .foregroundColor(Color("DarkPink")) } HStack { Text(data.name) .font(.body) .font(.system(size: 18)) .foregroundColor(Color.black) } HStack{ Image(systemName: "minus").resizable() .foregroundColor(self.subjectVM.setColorList(type: data)) .frame(width:70,height: 5) } } .frame(maxWidth: .infinity, alignment: .leading) .listRowInsets(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0)) .listRowBackground(Color.white) } } .listStyle(.plain)
如果需要适配iOS13及更早版本,将.listStyle(.plain)替换为.listStyle(PlainListStyle())即可。
内容的提问来源于stack exchange,提问作者GbRuiz
相关产品推荐
相关产品推荐

