【问题标题】:What are the benefits of using UIAppearance proxy instead of ordinary default values?使用 UIAppearance 代理而不是普通的默认值有什么好处?
【发布时间】:2016-05-11 10:50:12
【问题描述】:

请您解释一下,使用UIAppearance 代理对象来自定义我的UIView 子类属性而不是创建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 用法的文章中,他们说,更改此代理的属性允许类的实例自动获得相同的值。我不能完全掌握的是代理对象是否真的需要这个目的?在这种情况下使用静态变量来保存默认值有什么缺点吗?

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

 [CustomView appearance]setBackgroundColor:someNewColor];

用这个:

 [CustomView setDefaultBackgroundColor:someNewColor];

【问题讨论】:

    标签: ios objective-c uiappearance


    【解决方案1】:

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

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

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

    【讨论】:

    • 好吧,假设,我决定让这个子类在其他项目中可用。我不明白,使用[MyCustomView appearance]setBackgroundColor];[MyCustomView setDefaultBackgroundColor]; 有什么好处。在这两种情况下,我们只是为所有新实例提供默认颜色。我说的对吗?
    • @Storix 不一定。使用UIAppearance 协议,您可以精确控制何时使用appearanceWhenContainedInInstancesOf(或其他任何名称)使用某些样式。
    • 另外,我不确定,但我不知道在使用静态属性与外观时,自定义控件的子类化会如何影响样式。我不认为你不能轻易地扩展它?
    • 我想,在 Objective C 运行时的帮助下,结合静态变量实现与appearanceWhenContainedInInstancesOf 类似的方法并不难。但我对UIAppearance 代理的了解是它提供了下一个优点:1. 可读性和可维护性(由于代理设计模式,我们有统一的接口) 2. 我们不需要重新发明轮子 :) 谢谢你答案。
    • @Storix 是的,您绝对可以自己重新创建它。但是,已经为您创建了 UIAppearance :)
    猜你喜欢
    • 2013-03-22
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2012-04-13
    • 2010-09-14
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多