更改从xib加载的UITableViewHeaderFooterView上的背景颜色表示使用contentView.backgroundColor代替

Sen*_*ful 16 objective-c uitableview uiview ios

我正在从xib文件创建一个UITableViewHeaderFooterView,几乎所有东西都正常工作.

问题是,现在当我尝试更改背景颜色时(或者如果我在xib中配置了一个),它会不断地将此消息输出到控制台:

不推荐在UITableViewHeaderFooterView上设置背景颜色.请改用contentView.backgroundColor.

这意味着我有两个问题:

  • 如果我不想看到那个警告,我必须摆脱xib文件中的背景颜色.(这是不可取的,因为这意味着我的xib不再反映视图在运行时的样子).
  • 当我尝试通过代码更改背景颜色时,我得到了contentView.backgroundColor建议,但是当我尝试遵循该建议时,没有任何反应.(这是因为contentViewnil.)

注意:这里有一个类似的问题,但主要是关注消息,而不是找到解决上述两个问题的替代解决方案.

更新:要清楚,我想继续使用xib文件作为标题视图,并希望能够调用dequeueReusableHeaderFooterViewWithIdentifier:这样表可以有效地管理视图.

Sen*_*ful 18

这是我发现解决此问题的最佳方法:

  1. 将您的背景颜色重置UITableViewHeaderFooterView默认值.
  2. 直接在您的实例下添加一个视图UITableViewHeaderFooterView,并将其命名为Content View.(这正是Apple所做的UITableViewCell,我们只是模仿那个结构.)
  3. 您现在可以将内容视图的背景颜色更改为xib文件中的任何内容.
  4. 将任何其他意见insideContent View.
  5. contentView在扩展方法中重新定义属性,并添加IBOutlet到其定义中.(见下面的代码.)
  6. 将属性与您创建的内容视图相关联,就像使用任何IBOutlet一样.
  7. 您现在可以使用contentView.backgroundColor代码更改背景颜色,就像错误消息所示.

.h文件:

@interface ABCHeaderView : UITableViewHeaderFooterView
@end
Run Code Online (Sandbox Code Playgroud)

.m文件:

@interface ABCHeaderView ()

@property (nonatomic, readwrite, retain) IBOutlet UIView *contentView;

@end

@implementation ABCHeaderView

@synthesize contentView;

@end
Run Code Online (Sandbox Code Playgroud)

此层次结构与Apple的文档一致:

如果要显示自定义内容,请创建内容的子视图,并将其添加到contentView属性中的视图.


Hot*_*ard 9

要消除警告,您不能设置背景颜色.问题是当您以这种方式创建TableHeader时,IB不会为此提供特殊对象.删除源代码中的背景颜色将极好地解决所描述的问题,只需点击一下即可.

  1. 在Xcode中找到了头文件.xib
  2. 右键单击 - 打开为 - >源代码
  3. 找到颜色键:Cmd-F - "高建群"
  4. 去掉它.在我的情况下,这是线: <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
  5. 现在您可以更改背景,如:

    override func awakeFromNib() {
    
        backgroundView = UIView()
        backgroundView?.backgroundColor = UIColor.whiteColor()
    }
    
    Run Code Online (Sandbox Code Playgroud)


Nyc*_*cen 5

在 UITableViewHeaderFooterView 上设置背景颜色已被弃用。请改用 contentView.backgroundColor。

如果您在单独的 xib 文件中设计标头并在其中设置主 UIView 的背景,则可能会发生这种情况。

要解决此问题,请将 UIView 背景颜色恢复为 InterfaceBuilder 中的默认颜色,并在 viewForHeaderInSection:section 方法中设置背景颜色。

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderXibFileName") as! CustomHeader
    header.contentView.backgroundColor = UIColor.blueColor
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我们使用header.contentView.backgroundColorand not header.backgroundColor(这就是 xib 文件实际所做的)。