UIButtons的Objective C数组(包括初始化,动作等)

时间:2014-03-13 21:58:06

标签: ios objective-c uibutton ibaction

我在创建UI按钮数组时遇到了困难,而不是有很多单独的按钮。我试图创建四个并拥有:

ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {
    IBOutlet UIButton *b0;
    IBOutlet UIButton *b1;
    IBOutlet UIButton *b2;
    IBOutlet UIButton *b3;
}

@property (nonatomic, strong) UIButton *b0;
@property (nonatomic, strong) UIButton *b1;
@property (nonatomic, strong) UIButton *b2;
@property (nonatomic, strong) UIButton *b3;

@end

ViewController.m:

- (IBAction)b0Click:(id)sender {
    //Do something
}

- (IBAction)b1Click:(id)sender {
    //Do something
}

- (IBAction)b2Click:(id)sender {
    //Do something
}

- (IBAction)b3Click:(id)sender {
    //Do something
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

定义IBOutletCollection

@property (nonatomic, strong) IBOutletCollection(UIButton) buttons;

现在将所有按钮连接到此集合。

您现在可以通过以下方式访问按钮:

[self.buttons enumerateObjectsUsingBlock:^ (UIButton* button, NSUInteger index, BOOL* stop) {
//Do stuff here
}];

我必须警告你不要对数组中按钮的顺序做出假设。最好给每个按钮一个标签,然后在action方法中根据标签决定采用哪个代码路径。