2013-04-24 68 views
0

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

我正在寻找的东西,会像这样工作的Python伪代码:

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

什么是正确的Objective-C的方式做到这一点(假设我不想/不能小类这样的UI元素)?

回答

0

对于全局应用程序样式,可以考虑使用UIAppearance

对于特定的视图控制器,IBOutletCollection是最直接的方法 - 如果您使用IB,那就是。如果你不是,你可以创建一个NSArray变量或属性与你想要定制的所有按钮,然后迭代。

的Python代码最直译将

  1. 使用类别,例如添加一个方法来的UIButton -[UIButton(YMStyling) ym_stylize]
  2. 然后致电[@[button1, button2, button3] makeObjectsPerformSelector:@selector(ym_stylize)]

这在Cocoa/Obj-C世界里相当不自然,所以我会建议坚持上面更习惯的方法。当在罗马等...

+0

那么罗马人在Obj-C罗马做什么,他们使用IBOutletCollection? – syntagma 2013-04-24 17:26:47

+0

是的,我会这么认为;-)使用UIAppearance或IBOutletCollection。 – 2013-04-29 09:04:43

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
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 
    } 
} 
+0

我不能给杨的回答添加评论,所以我会在这里说: 您似乎在OP帖子中提出同样的问题,等你得到答案后。 – AlimovAndrei 2013-04-26 08:27:41