Swift如何更改列表中节标题的背景颜色?

Posted

技术标签:

【中文标题】Swift如何更改列表中节标题的背景颜色?【英文标题】:Swift how to change background color of a Section Header in a List? 【发布时间】:2021-02-23 22:52:51 【问题描述】:

我正在尝试更改此列表部分标题的背景颜色,以下仅对文本视图本身的背景进行着色。我也不想全局更改UITableView.appearance().backgroundColor,因为这会影响其他视图?

 List 
                            Section(header: Text("Summary")
                                        .font(.subheadline)
                                        .fontWeight(.medium)
                                        .background(Color.red).edgesIgnoringSafeArea(.all)
                            ) 
                                Text("\(filterThisMonthsWorkouts(workouts: athlyticDataStore.workouts).count) workouts")
                                    .font(.headline)
                                    .fontWeight(.medium)
                                    .font(Font.body.monospacedDigit())
                                Text("\(TimeFormatters().formatTimeAsDoubleToHoursAndMinutesOnly(duration: filterThisMonthsWorkouts(workouts: athlyticDataStore.workouts).map  $0.duration .reduce(0, +)))")
                                    .font(.headline)
                                    .fontWeight(.medium)
                                    .font(Font.body.monospacedDigit())
                                Text("\(Int(filterThisMonthsWorkouts(workouts: athlyticDataStore.workouts).map  $0.totalEnergyBurned .reduce(0, +))) calories burned")
                                    .font(.headline)
                                    .fontWeight(.medium)
                                    .font(Font.body.monospacedDigit())
                            
                        
                        .frame(height: sizeCategory > ContentSizeCategory.large ? 200 : 165)
                        .cornerRadius(10)
                        .listStyle(GroupedListStyle())
                        .padding([.horizontal, .top])

【问题讨论】:

【参考方案1】:

这可能会有所帮助:

 Text(...)   
   .frame(maxWidth: .infinity)

编辑: 以上适用于 Form,但使用 List 时,它的前导和尾随都有一些边缘,该区域与内容对齐。

把这个放在最后可以填满整个页眉宽度:

            Section(header: Text("hi")
                    .frame(maxWidth: .infinity)
                    .foregroundColor(.green)
                    .background(Color.red)
                    .listRowInsets(.init(top: -10, leading: -10, bottom: -10, trailing: -10)

【讨论】:

谢谢,它会扩展以填满列表的大部分宽度(还添加maxHeight: .infinity),但不幸的是它并没有填满标题所占据的整个区域。 它用现在而不是顶部或底部的高度填充整个标题 当您在该部分中添加选择器时会中断

以上是关于Swift如何更改列表中节标题的背景颜色?的主要内容,如果未能解决你的问题,请参考以下文章