如何在SwiftUI中为Form的Section添加彩色描边边框
问题根因
你之前的方案失效是因为SwiftUI中Form默认基于UIKit的UITableView实现,直接给Section添加background或overlay修饰符时,系统会将修饰符自动应用到Section内的每一行独立单元格上,不会作用于整个Section区块。
适配iOS14.5的解决方案
我们可以通过清除Form默认样式、自定义Section容器的方式实现全区块描边,完整可运行代码如下:
struct MyView: View { // 清除当前页Form默认的系统样式 init() { UITableView.appearance().backgroundColor = .clear UITableViewCell.appearance().backgroundColor = .clear UITableView.appearance().separatorStyle = .none } var body: some View { Form { Section { // 把Header和内容行都放进同一个VStack容器,统一加描边 VStack(alignment: .leading, spacing: 0) { Text("Section 1") .font(.subheadline) .foregroundColor(.secondary) .padding(.horizontal, 16) .padding(.vertical, 8) VStack(spacing: 0) { HStack { Text("Title 1.1") .foregroundColor(Color(.label)) Spacer() Text("Text 1.1") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) Divider() .padding(.leading, 16) HStack { Text("Title 1.2") .foregroundColor(Color(.label)) Spacer() Text("Text 1.2") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) Divider() .padding(.leading, 16) HStack { Text("Title 1.3") .foregroundColor(Color(.label)) Spacer() Text("Text 1.3") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) } // 给整个Section区块加黄色描边 .overlay( RoundedRectangle(cornerRadius: 16) .stroke(Color.yellow, lineWidth: 2) ) } // 清除系统行默认的内边距和背景 .listRowInsets(EdgeInsets()) .listRowBackground(Color.clear) } Section { VStack(alignment: .leading, spacing: 0) { Text("Section 2") .font(.subheadline) .foregroundColor(.secondary) .padding(.horizontal, 16) .padding(.vertical, 8) VStack(spacing: 0) { HStack { Text("Title 2.1") .foregroundColor(Color(.label)) Spacer() Text("Text 2.1") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) Divider() .padding(.leading, 16) HStack { Text("Title 2.2") .foregroundColor(Color(.label)) Spacer() Text("Text 2.2") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) Divider() .padding(.leading, 16) HStack { Text("Title 2.3") .foregroundColor(Color(.label)) Spacer() Text("Text 2.3") .lineLimit(1) .foregroundColor(Color(.label)) } .padding(.vertical, 12) .padding(.horizontal, 16) } .overlay( RoundedRectangle(cornerRadius: 16) .stroke(Color.yellow, lineWidth: 2) ) } .listRowInsets(EdgeInsets()) .listRowBackground(Color.clear) } } // 如果不想影响全局UITableView样式,可在这里加onDisappear还原系统默认外观 } }
内容的提问来源于stack exchange,提问作者iKK
相关产品推荐
相关产品推荐

