【问题标题】:How to share constants between Interface Builder and the code?如何在 Interface Builder 和代码之间共享常量?
【发布时间】:2010-12-10 18:44:27
【问题描述】:

我想知道是否有办法在 Interface Builder 中使用常量,例如为了避免在不同的地方手动设置相同的颜色(有时这可能是一项非常乏味的工作......)

目前我在代码中设置颜色并使用#define设置颜色,但是显然IB不能使用#define...

【问题讨论】:

    标签: iphone interface constants builder


    【解决方案1】:

    我通过子类化各种控件来解决这个问题,以确保整个应用程序的风格相同。缺点是你不能在界面生成器中看到样式,只有一个线框。

    例如我有一个

    @interface MyButton : UIButton 
    @end
    
    
    @implementation MyButton
    
     -(void) initialize{
    self.backgroundColor = [UIColor MyButonColor]; // Using a category on UIColor
    }
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self)  {
            [self initialize];
        }
        return self;
    }
    
    - (id)initWithCoder:(NSCoder *)decoder {
        if (self = [super initWithCoder:decoder]) {
            [self initialize];
        }
        return self;
    }
    

    【讨论】:

      【解决方案2】:

      我认为最简单的方法是在 UIColor 类上创建一个类别并在其上创建一个类方法。例如:

      将其放在头文件中(例如 UIColor+CustomColors.h):

      @interface UIColor ( CustomColors )
      + (UIColor *)myCustomColor;
      @end
      

      将它放在一个实现文件中(例如 UIColor+CustomColors.m)

      @implementation UIColor ( CustomColors )
      + (UIColor *)myCustomColor
      {
         return [UIColor colorWithRed:0.2 green:0.5 blue:0.2 alpha:1.0];
      }
      @end
      

      然后您可以在代码中的任何位置访问类方法,如下所示:

      ...
      self.view.backgroundColor = [UIColor myCustomColor];
      ...
      

      请参阅Apple's documentation on Categories 了解更多信息。

      或者,您可以通过系统调色板保存颜色样本。为此,您只需调用系统调色板,选择一种颜色并将其拖到颜色网格中。

      这些颜色现在不仅可以在您创建的每个 Interface Builder 文档中使用,而且可以在任何使用系统调色板的应用程序中使用。

      color palette http://img.skitch.com/20091030-dhh3tnfw5d8hkynyr7e5q3amwg.png

      【讨论】:

      • 感谢您的回答。实际上,我想在 IB 中设置颜色,而不是在代码中(这意味着我想避免 self.backgroundColor = myColor)。但是,如果我使用您提到的调色板中的自定义颜色,并且如果我想在将来修改我的颜色的蓝色百分比,我仍然必须在自定义颜色的任何地方在 IB 中手动进行更改已使用...我暂时保留我的#define 解决方案,它节省了我繁琐的重构时间...。
      猜你喜欢
      • 2011-03-09
      • 1970-01-01
      • 2023-03-17
      • 2013-02-11
      • 2017-09-09
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2014-07-07
      相关资源
      最近更新 更多