简体   繁体   English

UITableViewHeaderFooterView:无法更改背景颜色

[英]UITableViewHeaderFooterView: Unable to change background color

I'm trying to change the background color of UITableViewHeaderFooterView.我正在尝试更改 UITableViewHeaderFooterView 的背景颜色。 Although the view is appearing, the background color remains the default color.尽管视图正在出现,但背景颜色仍然是默认颜色。 I'm getting a log from xcode saying:我从 xcode 得到一个日志说:

Setting the background color on UITableViewHeaderFooterView has been deprecated.在 UITableViewHeaderFooterView 上设置背景颜色已被弃用。 Please use contentView.backgroundColor instead.请改用 contentView.backgroundColor。

However, none of the following options work:但是,以下选项均无效:

myTableViewHeaderFooterView.contentView.backgroundColor = [UIColor blackColor];
myTableViewHeaderFooterView.backgroundView.backgroundColor = [UIColor blackColor];
myTableViewHeaderFooterView.backgroundColor = [UIColor blackColor];

I've also tried changing the background color of the view in the xib file.我还尝试更改 xib 文件中视图的背景颜色。

Any suggestions?有什么建议么? Thanks.谢谢。

iOS 8, 9, 10, 11... iOS 8、9、10、11...

The only way to set any color (with any alpha) is to use backgroundView :设置任何颜色(使用任何 alpha)的唯一方法是使用backgroundView

Swift迅速

self.backgroundView = UIView(frame: self.bounds)
self.backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5)

Obj-C对象-C

self.backgroundView = ({
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor colorWithWhite: 0.5 alpha:0.5];
    view;
    });

Responses to Comments对评论的回应

  • None of these other options reliably work (despite the comments below)这些其他选项都不能可靠地工作(尽管有以下评论)

     // self.contentView.backgroundColor = [UIColor clearColor]; // self.backgroundColor = [UIColor clearColor]; // self.tintColor = [UIColor clearColor];
  • the backgroundView is resized automatically. backgroundView会自动调整大小。 (No need to add constraints) (无需添加约束)

  • Control alpha with UIColor(white: 0.5, alpha: 0.5) or backgroundView.alpha = 0.5 .使用UIColor(white: 0.5, alpha: 0.5)backgroundView.alpha = 0.5控制 alpha。
    (of course, any color will do) (当然,任何颜色都可以)

  • When using XIB , make root view a UITableViewHeaderFooterView and associate the backgroundView programmatically:使用XIB时,将根视图UITableViewHeaderFooterView并以编程方式关联backgroundView

    Register with:注册:

     tableView.register(UINib(nibName: "View", bundle: nil), forHeaderFooterViewReuseIdentifier: "header")

    Load with:加载:

     override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") { let backgroundView = UIView(frame: header.bounds) backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) header.backgroundView = backgroundView return header } return nil }

演示

↻ replay animation ↻ 重播动画

► Find this solution on GitHub and additional details on Swift Recipes . ► 在GitHub 上找到此解决方案,并在Swift Recipes上找到更多详细信息。

您应该使用myTableViewHeaderFooterView.tintColor ,或者将自定义背景视图分配给myTableViewHeaderFooterView.backgroundView

In iOS 7 contentView.backgroundColor worked for me, tintColor did not.在 iOS 7 contentView.backgroundColor为我工作, tintColor没有。

   headerView.contentView.backgroundColor = [UIColor blackColor];

Though clearColor did not work for me, the solution I found is to set backgroundView property to transparent image.虽然clearColor对我不起作用,但我找到的解决方案是将backgroundView属性设置为透明图像。 Maybe it will help someone:也许它会帮助某人:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

headerView.backgroundView = [[UIImageView alloc] initWithImage:blank];

Make sure you set the backgroundColor of the contentView for your UITableViewHeaderFooterView :确保为UITableViewHeaderFooterView设置contentView的 backgroundColor :

self.contentView.backgroundColor = [UIColor whiteColor];

Then it will work.然后它将起作用。

For me I tried everything stated above but still was getting the warning "Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead."对我来说,我尝试了上述所有方法,但仍然收到警告“在 UITableViewHeaderFooterView 上设置背景颜色已被弃用。请改用 contentView.backgroundColor。” then I tried this: within the xib file the background color for header view was selected to clear color instead of default once I changed it to default the warning went away.然后我尝试了这个:在 xib 文件中,标题视图的背景颜色被选择为清除颜色而不是默认颜色,一旦我将其更改为默认值,警告就消失了。 这是

改成这个

For solid background colors, setting the contentView.backgroundColor should be enough:对于纯色背景色,设置contentView.backgroundColor就足够了:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.contentView.backgroundColor = .red // Works!
    }
}

For colors with transparency, including .clear color, this no longer works:对于具有透明度的颜色,包括.clear颜色,这不再有效:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.contentView.backgroundColor = .clear // Does not work 😞
    }
}

For a full transparent section header, set the backgroundView property to an empty view:对于完全透明的部分标题,请将backgroundView属性设置为空视图:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.backgroundView = UIView() // Works!
    }
}

However, beware of possible side effects.但是,请注意可能的副作用。 Unless the table view is set to "Grouped", section headers will snap at the top when scrolling down.除非表格视图设置为“分组”,否则当向下滚动时,部分标题将在顶部对齐。 If the section headers are transparent, the cell content will be seen through, which might not look great.如果部分标题是透明的,则单元格内容将被看穿,这可能看起来不太好。

Here, section headers have transparent background:在这里,节标题具有透明背景:

在此处输入图像描述

To prevent this, it is better to set the background of the section header to a solid color (or gradient) matching the background of your table view or view controller.为了防止这种情况,最好将节标题的背景设置为与表格视图或视图控制器的背景相匹配的纯色(或渐变)。

Here, section headers have a fully opaque gradient background:在这里,节标题具有完全不透明的渐变背景:

在此处输入图像描述

For a clear color, I use为了清晰的颜色,我使用

self.contentView.backgroundColor = [UIColor clearColor];
self.backgroundView = [UIView new];
self.backgroundView.backgroundColor = [UIColor clearColor];

It seems fine to me.对我来说似乎很好。

在此处输入图像描述 In interface builder pull up your .xib, on the top element, in attribute inspector set the background color to default.在界面生成器中,在顶部元素上拉起您的 .xib,在属性检查器中将背景颜色设置为默认值。 Then go to the Content View and set the background color there (reference to https://github.com/jiecao-fm/SwiftTheme/issues/24 ).然后转到 Content View 并在那里设置背景颜色(参考https://github.com/jiecao-fm/SwiftTheme/issues/24 )。

On iOS9 headerView.backgroundView.backgroundColor worked for me:iOS9 headerView.backgroundView.backgroundColor为我工作:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TableViewHeader *headerView = (TableViewHeader *)[super tableView:tableView viewForHeaderInSection:section];
    headerView.backgroundView.backgroundColor = [UIColor redColor];
}

On iOS8 I was using headerView.contentView.backgroundColor without problems, but now with iOS 9, I was getting a weird issue that made the background color not fill the whole space of the cell.iOS8 上,我使用headerView.contentView.backgroundColor没有问题,但现在在 iOS 9 上,我遇到了一个奇怪的问题,即背景颜色没有填满单元格的整个空间。 So I tried just headerView.backgroundColor and I got the same error from the OP.所以我只尝试了headerView.backgroundColor并且我从 OP 得到了同样的错误。

Setting the background color on UITableViewHeaderFooterView has been deprecated.在 UITableViewHeaderFooterView 上设置背景颜色已被弃用。 Please use contentView.backgroundColor instead.请改用 contentView.backgroundColor。

So now everything works great and without warnings by using headerView.backgroundView.backgroundColor所以现在一切正常,使用headerView.backgroundView.backgroundColor

If you are customising a section header cell with Storyboard/Nib , then make sure the background color is default for the "Table Section Header" view.如果您使用 Storyboard/Nib 自定义节标题单元格,请确保背景颜色是“表节标题”视图的默认颜色。

And if you subclass UITableViewHeaderFooterView , and using nib, then what you have to do is to create a IBOutlet for the content view, and name it eg.如果您UITableViewHeaderFooterView并使用 nib,那么您要做的就是为内容视图创建一个IBOutlet ,并将其命名为例如。 containerView . containerView This is not to be confused with contentView , which is parent of this container view.这不应与contentView混淆,后者是该容器视图的父级。

With that setup, you change the background color of containerView instead.通过该设置,您可以更改containerView的背景颜色。

if you created a custom subclass of UITableViewHeaderFooterView with xib file then you should override setBackgroundColor .如果您使用xib文件创建了UITableViewHeaderFooterView的自定义子类,那么您应该覆盖setBackgroundColor Keep it empty.保持空白。

-(void)setBackgroundColor:(UIColor *)backgroundColor {

}

And this will solve your problem.这将解决您的问题。

I tried with the appearanceWhenContainedIn chain, and it worked for me.我尝试了外观当包含在链中,它对我有用。

[[UIView appearanceWhenContainedIn:[UITableViewHeaderFooterView class], [UITableView class], nil] 
         setBackgroundColor: [UIColor.grayColor]];

maybe because the backgroundView doesn't exist可能是因为 backgroundView 不存在

override func draw(_ rect: CGRect){
    // Drawing code
    let view = UIView()
    view.frame = rect
    self.backgroundView = view
    self.backgroundView?.backgroundColor = UIColor.yourColorHere
}

that work for me.那对我有用。

iOS 12, Swift 5. If you are willing (or trying!) to use an appearance proxy, the following solution works: iOS 12,Swift 5。如果您愿意(或尝试!)使用外观代理,以下解决方案有效:

  1. Subclass UITableViewHeaderFooterView and expose your own appearance proxy setting.子类 UITableViewHeaderFooterView 并公开您自己的外观代理设置。
final class MySectionHeaderView: UITableViewHeaderFooterView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
    }

    @objc dynamic var forceBackgroundColor: UIColor? {
        get { return self.contentView.backgroundColor }
        set(color) {
            self.contentView.backgroundColor = color
            // if your color is not opaque, adjust backgroundView as well
            self.backgroundView?.backgroundColor = .clear
        }
    }
}
  1. Set the appearance proxy at your desired granularity.以所需的粒度设置外观代理。
MySectionHeaderView.appearance().forceBackgroundColor = .red

or或者

MySectionHeaderView.appearance(whenContainedInInstancesOf: [MyOtherClass.self]).forceBackgroundColor = .red

Forget about difficulties.忘记困难。

Add to your project UITableViewHeaderFooterView+BGUpdate.swift with code below:使用以下代码将UITableViewHeaderFooterView+BGUpdate.swift添加到您的项目中:

extension UITableViewHeaderFooterView {

    open override var backgroundColor: UIColor? {
        get {
            return self.backgroundColor
        }
        set {
            let bgView = UIView()
            bgView.backgroundColor = newValue
            backgroundView = bgView
        }
    }
}

Usage is simple as you expected before:用法很简单,正如您之前预期的那样:

headerView.backgroundColor = .red

Usage examples :用法示例

1) In delegate's tableView:viewForHeaderInSection: : 1) 在委托的tableView:viewForHeaderInSection:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tv.dequeueReusableHeaderFooterView(withIdentifier: "MyHeaderView")
    headerView.backgroundColor = .red // <- here
    return headerView
}

or或者

2) In your custom header view class: 2)在您的自定义标题视图类中:

class MyHeaderView: UITableViewHeaderFooterView {

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .red // <- here
    }
}

Put this code in initializing of your UITableViewHeaderFooterView subclass:将此代码放入UITableViewHeaderFooterView子类的初始化中:

let bgView = UIView()
bgView.backgroundColor = UIColor.clear
backgroundView = bgView
backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear

Setting the BackgroundView with clear color works fine for visible headers.用清晰的颜色设置 BackgroundView 对于可见的标题效果很好。 If the table is scrolled to show headers at bottom ,this solution fails.如果滚动表格以在底部显示标题,则此解决方案将失败。

PSMy table consists only of headers without any cells. PSMy 表仅包含没有任何单元格的标题。

Swift:迅速:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView {
    var headerView: TableViewHeader = super.tableView(tableView, viewForHeaderInSection: section) as! TableViewHeader
    headerView.backgroundView.backgroundColor = UIColor.redColor()
}

Create UIView and set background color, then set it to self.backgroundView.创建 UIView 并设置背景颜色,然后将其设置为 self.backgroundView。

- (void)setupBackgroundColor:(UIColor *) color {
    UIView *bgView = [[UIView alloc] initWithFrame:self.bounds];
    bgView.backgroundColor = color;
    self.backgroundView = bgView;
}

I feel compelled to share my experience.我觉得有必要分享我的经验。 I had this piece of code that worked fine with iOS 10 and iOS 11 headerView?.contentView.backgroundColor = .lightGray我的这段代码在 iOS 10 和 iOS 11 headerView?.contentView.backgroundColor = .lightGray

Then I all of a sudden decided to to deploy the app for iOS 9 as there are some devices (iPad mini some older generation doesn't update to any OS beyond 9) - The only solution that worked for all iOS 9, 10 and 11 was to define a base view for the header that then contains all other header subviews, wire it up from storyboard and set the backgroundColor of that base view.然后我突然决定为 iOS 9 部署应用程序,因为有一些设备(iPad mini 一些老一代不会更新到任何超过 9 的操作系统) - 适用于所有 iOS 9、10 和 11 的唯一解决方案是为标题定义一个基本视图,然后包含所有其他标题子视图,从情节提要连接它并设置该基本视图的backgroundColor颜色。

You will want to be mindful when wiring the outlet not to call it: backgroundView as there is already a property with that name in some superclass .在连接插座时要注意不要调用它: backgroundView因为在某个superclass中已经有一个具有该名称的属性。 I called mine containingView我打电话给我containingView

Also when wiring the outlet control click on the view in Document Outline to make sure it's not wired up to file owner此外,在连接插座控件时,单击Document Outline中的视图以确保它没有连接到file owner

Now since iOS 14 we've got UIBackgroundConfiguration for UITableViewHeaderFooterView.现在从 iOS 14 开始,我们为 UITableViewHeaderFooterView 提供了 UIBackgroundConfiguration。

To change the background color I'm doing the following:要更改背景颜色,我正在执行以下操作:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? LeftMenuSectionHeader {
        if var backgroundConfig = headerView.backgroundConfiguration {
            backgroundConfig.backgroundColor = UIColor.clear
            headerView.backgroundConfiguration = backgroundConfig
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM