NSHipster Obscure Topics in Cocoa and Objective C

UIAppearance

UIAppearance allows the appearance of views and controls to be consistently customized across the entire application.

In order to have this work within the existing structure of UIKit, Apple devised a rather clever solution: UIAppearance is a protocol that returns a proxy which forwards any configuration to every instance of a particular class.

Why a proxy instead of a property or method on UIView directly? Because there are non-UIView objects like UIBarButtonItem that render their own composite views.

+appearance

(改变自定义类的所有实例的外观) To customize the appearance of all instances of a class, you use appearance to get the appearance proxy for the class. For example, to modify the tint color for all instances of UINavigationBar:

[[UINavigationBar appearance] setTintColor:myColor];

+appearanceWhenContainedIn:

(改变自定义类的所有实例的外观) To customize the appearances in a way that adjusts for being contained within an instance of a container class, or instances in a hierarchy, you use appearanceWhenContainedIn: to get the appearance proxy for the class:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:myNavBarColor];

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:myPopoverNavBarColor];

[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil] setTintColor:myToolbarColor];

[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], [UIPopoverController class], nil] setTintColor:myPopoverToolbarColor];