将相同的UI更改应用于许多元素

时间:2013-04-24 08:03:41

标签: ios objective-c user-interface interface-builder

我经常遇到的一个问题是如何对同一视图中的许多UI元素应用相同的更改。

我正在寻找的东西就像这个Python伪代码一样:

def stylize(element): 
    # apply all the UI changes to an element
elements = [button1, button2, button3]
map(stylize,elements)

正确的Objective-C方法是什么(假设我不想/不能将这些UI元素子类化)?

3 个答案:

答案 0 :(得分:0)

我不知道Python也完全不理解你的问题。我不清楚。

可能您正在寻找IBOutletCollection

  

<强> IBOutletCollection

Identifier used to qualify a one-to-many instance-variable declaration so that Interface Builder can synchronize the display and connection of outlets with Xcode. You can insert this macro only in front of variables typed as NSArray or NSMutableArray.

This macro takes an optional ClassName parameter. If specified, Interface Builder requires all objects added to the array to be instances of that class. For example, to define a property that stores only UIView objects, you could use a declaration similar to the following:

@property (nonatomic, retain) IBOutletCollection(UIView) NSArray *views;

For additional examples of how to declare outlets, including how to create outlets with the @property syntax, see “Xcode Integration”.

Available in iOS 4.0 and later.

Declared in UINibDeclarations.h.
     

讨论

     

有关如何使用这些常量的更多信息,请参阅   “与对象进行通信”。有关定义和使用的信息   Interface Builder中的操作和出口,请参阅Interface Builder用户   指南。

检查以下链接:

  1. UIKitConstantsReference
  2. Using iOS 4′s IBOutletCollection

答案 1 :(得分:0)

对于全局应用样式,请考虑使用UIAppearance

对于特定的视图控制器,IBOutletCollection是最简单的方法 - 如果你使用的是IB,那就是。如果不是,您可以创建一个NSArray变量或属性,其中包含您要自定义的所有按钮,然后迭代它。

Python代码的最直译是

  1. 使用类别向UIButton添加方法,例如-[UIButton(YMStyling) ym_stylize]
  2. 然后致电[@[button1, button2, button3] makeObjectsPerformSelector:@selector(ym_stylize)]
  3. 这在Cocoa / Obj-C世界中相当不自然,所以我建议坚持上面更惯用的方法。在罗马等等...

答案 2 :(得分:0)

我想你可以简单地使用带有视图的NSMutableArray。以下是我展示自己想法的一个例子:

- (void)viewDidLoad {

    [super viewDidLoad];

    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 20, 40)];
    [view1 setBackgroundColor:[UIColor blackColor]];
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(150, 100, 20, 40)];
    [view2 setBackgroundColor:[UIColor whiteColor]];
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(200, 100, 20, 40)];
    [view3 setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:view1];
    [self.view addSubview:view2];
    [self.view addSubview:view3];

    NSMutableArray *views = [NSMutableArray arrayWithObjects:view1, view2, view3, nil];

    [self changeViews:views];
}

-(void)changeViews:(NSMutableArray *)viewsArray {
    for (UIView *view in viewsArray) {
        [view setBackgroundColor:[UIColor blueColor]];//any changes you want to perform
    }
}