Search code examples
iosuitableviewuiappearance

UIAppearance instances in hierarchy


From Apple's document about UIAppearance:

To customize the appearances for instances of a class contained within an instance of a container class, or instances in a hierarchy, use +appearanceWhenContainedIn: for the appropriate appearance proxy.

In any given view hierarchy the outermost appearance proxy wins. Specificity (depth of the chain) is the tie-breaker.

In other words, the containment statement is treated as a partial ordering. Given a concrete ordering (actual subview hierarchy), we select the partial ordering that is the first unique match when reading the actual hierarchy from the window down.

Can somebody given an example for the case where a hierarchy could be specified?

Consider the case that I wish to style UITableViewCells for only a particular UITableViewController subclass's instance

[[UITableViewCell appearance] setTintColor:[UIColor whiteColor]];

But only for one of the SomeXYZTableViewController's instances, i.e. for two different instances of SomeXYZTableViewController, I want a different tint color.

There are tons of other ways to do this, but I am simply wondering if it's possible.


Solution

  • But only for one of the SomeXYZTableViewController's instances

    That's certainly possible, but let's take an easier and more probable way of doing this. You could subclass UITableView. Let's call the subclass WhiteTableView. It does nothing; it's just a subclass. You would make one of your table views a WhiteTableView.

    So now you could specify that table view cells should have a white tint color but only when they are inside a WhiteTableView.

    The example I give in my book - from real life - is:

    [[UIBarButtonItem appearance]
        setTintColor: [UIColor myGolden]];
    [[UIBarButtonItem appearanceWhenContainedIn:
        [UIToolbar class], nil]
            setTintColor: [UIColor myPaler]];
    [[UIBarButtonItem appearanceWhenContainedIn:
        [UIToolbar class], [DrillViewController class], nil]
            setTintColor: [UIColor myGolden]];
    

    That means:

    1. In general, bar button items should be tinted golden.

    2. But bar button items in a toolbar are an exception: they should be paler.

    3. But bar button items in a toolbar in DrillViewController’s view are an exception to the exception: they should be golden.