SwiftUI:如何修改List顶部分隔线的leading inset?
解决SwiftUI List顶部行分隔线Leading内边距调整问题
自iOS 16起,SwiftUI的List会自动调整行内边距,让分隔线与文本的leading边缘对齐。如果想要实现像Messages.app那样的顶部行分隔线leading内边距效果,可以试试以下两种方案:
隐藏系统分隔线,自定义分隔线
先通过listRowSeparator(.hidden)隐藏系统默认分隔线,再在每个行视图中添加自定义分隔线,针对第一行单独设置leading内边距:struct CustomList: View { let items = ["Item 1", "Item 2", "Item 3"] var body: some View { List(items.indices, id: \.self) { index in HStack { Text(items[index]) } .listRowSeparator(.hidden) .overlay( Divider() .padding(.leading, index == 0 ? 80 : 16) // 第一行设置更大的leading内边距,匹配Messages效果 .alignmentGuide(.bottom) { $0[.bottom] }, alignment: .bottom ) } } }利用
listRowSeparatorInsets针对首行设置
iOS 16及以上原生支持listRowSeparatorInsets修饰符,可直接为指定行设置分隔线内边距,无需自定义分隔线:struct CustomList: View { let items = ["Item 1", "Item 2", "Item 3"] var body: some View { List(items.indices, id: \.self) { index in Text(items[index]) .listRowSeparatorInsets(EdgeInsets(top: 0, leading: index == 0 ? 80 : 16, bottom: 0, trailing: 0)) } } }
你之前尝试的alignmentGuide(_:computeValue:)之所以没生效,是因为它主要用于调整视图自身的对齐逻辑,无法影响List系统分隔线的布局规则,系统分隔线的位置由List的行布局逻辑直接控制,所以需要用上述两种方式针对性调整。
内容的提问来源于stack exchange,提问作者Viktoriia
相关产品推荐
相关产品推荐

