Search code examples
iosswiftuitableviewuiviewuiappearance

iOS: Override UIAppearance appearanceWhenContainedInInstancesOfClasses


I have a global theme applied that changes the background color of a UITableViewHeaderFooterView. Below is the code:

[[UIView appearanceWhenContainedInInstancesOfClasses:@[[UITableViewHeaderFooterView class]]] setBackgroundColor:[UIColor lightGray]];

There is an instance on one screen, where I wish to override this color and change the color to white. I have tried the following code:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderView") as? HeaderView

    headerView.contentView.backgroundColor = UIColor.white
    headerView.backgroundColor = UIColor.white

    return headerView
}

However, the headerView still appears with a light gray background. Any ideas on how to override it?


Solution

  • You can make a subclass of UITableViewHeaderFooterView - say WhiteUITableViewHeaderFooterView and configure that for the correct header.

    Then, you can set the appearance for views in that class [[UIView appearanceWhenContainedInInstancesOfClasses:@[[WhiteUITableViewHeaderFooterView class]]] setBackgroundColor:[UIColor white]];