使用 UIAppearance 代理代替普通的默认值有什么好处?

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

请你解释一下,使用 UIAppearance 代理对象自定义我的 UIView subclass 属性而不是创建 setter 有什么好处提供所需默认值的方法,如以下代码示例所示:

@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

在我读过的所有关于 UIAppearance 用法的文章中,他们说,更改此代理的属性允许 class 的实例自动获得相同的值。我不能完全理解的是代理对象是否真的需要用于此目的?在这种情况下使用静态变量来保存默认值有什么缺点吗?

为了让事情更清楚,我正在比较这种方法:

 [CustomView appearance]setBackgroundColor:someNewColor];

有了这个:

 [CustomView setDefaultBackgroundColor:someNewColor];

这不是 UIAppearance 的真正用例。如果您编写的 UIView 子类仅用于单个项目,那么只需使其看起来像您想要的那样即可。

UIAppearance 如果您决定让该子类在您的所有项目中都可用,并且可能需要为每个项目专门设置样式,那么它就在那里。或者,如果您想使用它的大量实例而不必单独设置每个实例的样式。

UILabel 的工作方式类似。它是一个 UIView 子类,旨在用于各种不同的项目。