2013-04-24 65 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