IBOutletCollection

来源:互联网 发布:mysql order by desc 编辑:程序博客网 时间:2024/06/05 01:52
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *weightUnit_lbls;


for (UILabel *lbl in self.weightUnit_lbls) {
    lbl.text = @"lbs";
}


今天在看IB User Guide的时候看到了一个新的关键字IBOutletCollection。字面上的意思就挺明显的,之前要是需要用IB加n个按钮或者别的什么widgets,都要先定义n个IBOutlet,然后在IB里面一个一个地连接好。现在可好了,有IBOutletCollection定义一个NSArray的按钮,在IB里面全部连过去,快捷方便。
原文如下:
In Mac OS X and iPhone OS v3.3 and earlier, you can connect an outlet to only a single object. However, starting with iPhone OS v3.4, you can connect an outlet to multiple objects. To do so, use the IBOutletCollection keyword. For example, to connect a view controller to multiple objects of type UILabel, you could add the following code in Xcode:


@interface MyController : UIViewController {
    IBOutletCollection (UILabel) NSArray* multipleLabels;
}
@end
If the output targets are not all the same kind of object, use id for the object type in the declaration, or omit the object type in the parentheses following IBObjectCollection; for example:


@interface MyController : UIViewController {
    IBOutletCollection (id) NSArray* multipleObjects;
}
@end
嗯,不过iPhone OS v3.4指的应该是iOS4吧。。
iOS 4.0 的 SDK 多了一個新的關鍵字,叫做 IBOutletCollection,於是你可以將一個單一的成員變數,連結到許多的 UI 元件的實體上。
或這麼說,以前如果想要在我們的 iPhone 程式裡,在某個畫面中,放置四個標籤元件(UILabel),然後想要改變這些標籤中的文字內容,我們會在 header 裡頭這樣宣告:
@interface MyViewController : UIViewController {
    UILabel *label1;
    UILabel *label2;
    UILabel *label3;
    UILabel *label4;
}
 
@property (retain, nonatomic) IBOutletCollection UILabel *label1;
@property (retain, nonatomic) IBOutletCollection UILabel *label2;
@property (retain, nonatomic) IBOutletCollection UILabel *label3;
@property (retain, nonatomic) IBOutletCollection UILabel *label4;
@end
然後分別連結這四個 label。而現在,你可以這樣宣告:




@interface MyViewController : UIViewController {
    NSArray *labels;
}
@property (retain, nonatomic) IBOutletCollection (UILabel) NSArray *labels;
@end


在 IB 中,只要是 UILabel 類別的物件,都可以與 lables 連結。接著,你就可以用任何可以對 NSArray 的操作方式,處理畫面中的 UI 元件,比方說,你可以用點 KVC,直接用一行程式碼,就改變多個 UILabel 的文字內容,像這樣-


[labels setValue:@"1234" forKeyPath:@"text"];


原文来自:
http://www.igniu.com/?p=125
http://zonble.net/archives/2010_07/1333.php