Search code examples
iosobjective-cuiappearance

What are the benefits of using UIAppearance proxy instead of ordinary default values?


Could you explain me, please, what would be the benefits of using UIAppearance proxy object to customize my UIView subclass properties instead of creating the setter methods to provide the required default values like in the following code sample:

@interface CustomView : UIView

+ (void)setDefaultBackgroundColor: (UIColor *)defaultBackgroundColor;

@end

@implementation CustomView

static UIColor *defaultBackgroundColor_ = nil;

- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    if (!defaultBackgroundColor_)
      defaultBackgroundColor_ = [UIColor blackColor];
  }
  return self;
}

+ (void)setDefaultBackgroundColor: (UIColor *)defaultBackgroundColor {
  defaultBackgroundColor_ = defaultBackgroundColor;
}

@end

In all the articles I've read about UIAppearance usage they say, that changing the properties of this proxy allows the instances of the class to get the same value automatically. What I cannot fully grasp is whether the proxy object is really required for this purpose? Are there any downsides of using the static vars to hold the default values in this case?

To make things more clear, I'm comparing this approach:

 [CustomView appearance]setBackgroundColor:someNewColor];

with this:

 [CustomView setDefaultBackgroundColor:someNewColor];

Solution

  • This is not really the use case for UIAppearance. If you are writing a UIView subclass to only be used in a single project then just make it look the way you want.

    UIAppearance is there for if you decide to make that subclass usable in all of your projects and it might need to be styled for each project specifically. Or if you want to use lots of instances of it without having to set the style of each individually.

    Similarly to how UILabel works. It's a UIView subclass designed to be used in all sorts of different projects.