SwiftUI中如何创建直角List?解决列表边角被裁剪问题
SwiftUI 实现直角List组件(解决边角裁剪问题)
问题分析
List组件默认带有圆角裁剪逻辑,导致你给每行添加的.stroke()修饰符边角被裁切,无法显示完整的直角边框。
解决方案
通过以下调整实现完整的直角列表:
- 取消List默认的圆角样式,改用Plain列表样式
- 隐藏List默认背景,避免遮挡外层边框
- 用外层容器实现整体直角边框,每行仅添加底部分隔边框,避免重复绘制边框
修改后的代码
struct SwiftUIView: View { var body: some View { VStack(spacing: 0) { Text("this is a text") Spacer() // 外层容器提供整体直角边框 Rectangle() .stroke(Color.red, lineWidth: 2) .overlay( List { ForEach(1..<5) { item in HStack { Text("item\(item)") .scaleEffect(CGSize(width: 1.0, height: -1.0)) } .listRowInsets(EdgeInsets()) .frame(height: 50) .frame(maxWidth: .infinity) // 每行添加底部边框作为分隔 .overlay( Rectangle() .stroke(Color.red, lineWidth: 2) .frame(height: 2), alignment: .bottom ) } } .listStyle(.plain) // 取消默认分组圆角 .scrollContentBackground(.hidden) // 隐藏List默认背景 ) .frame(height: 500) .scaleEffect(CGSize(width: 1.0, height: -1.0)) } } }
补充说明
- 若不需要每行分隔线,可直接移除每行的底部边框代码,仅保留外层容器的直角边框
- 针对iOS 15及以下版本,可将
.scrollContentBackground(.hidden)替换为.background(Color.clear)来隐藏List默认背景
内容的提问来源于stack exchange,提问作者Alpha
相关产品推荐
相关产品推荐

