SwiftUI List分隔线问题:行首非Text组件时左侧出现多余缩进
解决SwiftUI List分隔线无法贯穿整行的问题
方法一:调整列表行内边距
给每个列表行添加listRowInsets修饰符,将内边距设为0,系统默认的分隔线就会贯穿整行。如果需要保留行内容的左右间距,可以手动添加padding:
struct ContentView: View { var body: some View { List { HStack{ Image(systemName: "star") .frame(width: 50, height: 50) Text("Chocolate") } .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0)) .padding(.horizontal, 16) // 按需添加左右内边距 HStack{ Image(systemName: "star") .frame(width: 50, height: 50) Text("Waffles") } .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0)) .padding(.horizontal, 16) } } }
方法二:自定义分隔线
隐藏系统默认分隔线,手动添加自定义的Divider组件,完全控制分隔线的显示范围:
struct ContentView: View { var body: some View { List { VStack(spacing: 0) { HStack{ Image(systemName: "star") .frame(width: 50, height: 50) Text("Chocolate") } Divider() // 自定义分隔线,默认贯穿整行 } VStack(spacing: 0) { HStack{ Image(systemName: "star") .frame(width: 50, height: 50) Text("Waffles") } Divider() } } .listStyle(.plain) // 隐藏系统默认分隔线 } }
如果需要更灵活的分隔线样式,还可以给Divider添加修饰符调整颜色、粗细等:
Divider() .foregroundColor(.gray) .frame(height: 1)
内容的提问来源于stack exchange,提问作者Farid
相关产品推荐
相关产品推荐

