You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS15下SwiftUI设置SidebarListStyle样式List的背景色失效(iOS14正常)

问题原因

  • 这不是iOS15或SwiftUI的Bug,是iOS15对UITableView做了API变更,新增了UIBackgroundConfiguration默认背景配置,会覆盖直接设置的backgroundColor属性
  • SidebarListStyle在iOS15下的List默认会自带系统侧边栏背景样式,直接添加SwiftUI的.background()修饰符会被List内部的行背景、容器背景遮盖,因此不会生效
  • 全局设置UITableView.appearance()会影响所有列表,不符合单个列表修改的需求,不建议使用

适配解决方案

方案1:兼容现有Introspect依赖的最小改动方案

仅修改Introspect闭包内的逻辑即可同时适配iOS14、iOS15+,不会影响其他UITableView:

.introspectTableView { tableView in
    let targetColor = UIColor(Color.blue)
    if #available(iOS 15.0, *) {
        // 清空系统默认背景配置
        tableView.backgroundView = UIView()
        tableView.backgroundView?.backgroundColor = targetColor
        tableView.sectionHeaderTopPadding = 0
        // 清空cell的默认背景配置
        tableView.cellLayoutMarginsFollowReadableWidth = false
    } else {
        tableView.backgroundColor = targetColor
    }
}
// 额外添加行背景修饰符,统一行背景色
.listRowBackground(Color.blue)

方案2:纯SwiftUI原生适配(iOS15+)

不需要依赖Introspect库,直接用系统修饰符组合实现:

List {
    // ... 原有列表内容
}
.listStyle(SidebarListStyle())
.scrollContentBackground(.hidden) // 隐藏List默认的滚动内容背景
.background(Color.blue)
.listRowBackground(Color.blue) // 设置所有行的背景色
.accentColor(.white)
// 其他原有修饰符

若需要兼容iOS15以下版本,可将scrollContentBackground用if #available(iOS 16.0, *)包裹,低版本依然走原有Introspect逻辑即可。

和SidebarListStyle的关联

该问题确实和你使用的SidebarListStyle有关:这种列表样式在iOS15开始默认会套用系统侧边栏的磨砂背景、行样式等预设配置,优先级高于开发者直接设置的普通background属性,所以需要先清空系统默认的背景配置才能让自定义背景生效。

内容的提问来源于stack exchange,提问作者Shadowman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:45:07