SwiftUI列表选中项高亮栏自定义颜色实现咨询
SwiftUI列表选中项高亮栏自定义颜色实现咨询
嗨,刚接触SwiftUI遇到这种样式定制问题太正常啦~ 你的需求其实有几种实用的实现方式,我给你详细说说:
方法一:全局设置(适合快速修改,iOS全版本兼容)
这种方式利用UIKit的外观代理来修改,代码量最少,但会影响整个APP里的所有List选中样式:
struct Test: View { @State private var selection: String? let names = ["Cyril", "Lana", "Mallory", "Sterling"] init() { // 替换成你想要的颜色,比如.systemPink、.orange等 UITableViewCell.appearance().selectedBackgroundView = UIView().then { $0.backgroundColor = .systemPink } } var body: some View { NavigationStack { List(names, id: \.self, selection: $selection) { name in Text(name) } .navigationTitle("List Selection") } } } // 可选小扩展:简化代码写法,不用也没关系 extension UIView { func then(_ configure: (Self) -> Void) -> Self { configure(self) return self } }
方法二:自定义Cell(局部定制,不影响全局)
如果你只想让这个特定的List有自定义选中色,推荐用这种方式,自己控制Cell的背景状态:
struct Test: View { @State private var selection: String? let names = ["Cyril", "Lana", "Mallory", "Sterling"] var body: some View { NavigationStack { List(names, id: \.self, selection: $selection) { name in CustomListCell(name: name, isSelected: selection == name) } .navigationTitle("List Selection") .environment(\.defaultMinListRowHeight, 44) // 保持系统默认行高 } } } struct CustomListCell: View { let name: String let isSelected: Bool var body: some View { Text(name) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) .background(isSelected ? Color.systemGreen : Color.clear) .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) // 匹配系统默认内边距 } }
方法三:iOS 16+专属简化写法
如果你的APP只需要支持iOS 16及以上版本,直接用listRowBackground就能快速实现,不用额外写Cell:
struct Test: View { @State private var selection: String? let names = ["Cyril", "Lana", "Mallory", "Sterling"] var body: some View { NavigationStack { List(names, id: \.self, selection: $selection) { name in Text(name) // 选中时显示自定义颜色,未选中时用透明色 .listRowBackground(selection == name ? Color.orange : Color.clear) } .navigationTitle("List Selection") } } }
你可以根据自己的iOS版本兼容性需求和样式范围(全局/局部)来选择对应的方法哦~
备注:内容来源于stack exchange,提问作者Spanners
相关产品推荐
相关产品推荐

