我一直在开发一款应用程序,我手动在IB中创建了十几个按钮。我现在想重新开始,并在代码中做所有事情,因为我需要动态的按钮数量。我还想做其他事情,比如手动控制它们出现的地方等等。
MainViewController.h
中的:
@property (nonatomic, retain) IBOutlet UIButton *startButton;
@property (nonatomic, retain) IBOutlet UIButton *stopButton;
@property (nonatomic, retain) IBOutletCollection(UIButton) NSMutableArray *tiles;
- (IBAction) tilePressed:(id)sender;
- (void) initTiles;
MainViewController.m
中的
- (void)viewDidLoad
{
[super viewDidLoad];
[self initTiles];
}
- (void)viewDidUnload
{
[self setStartButton:nil];
[self setStopButton:nil];
[self setTiles:nil];
[super viewDidUnload];
}
-(void)initTiles
{
//tiles = [[NSMutableArray alloc] initWithCapacity:5];
for (int count = 0; count < 5; count++)
{ //I used tiles.count here, but that fails
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(count*10+10, 10, 10, 10)];
[b setTitle:[NSString stringWithFormat:@"%i",count+1] forState:UIControlStateNormal];
[b setTag:count];
[b setHidden:NO];
[b addTarget:self action:@selector(tilePressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
}
-(IBAction)tilePressed:(id)sender {
NSLog(@"button pressed: %i", [sender tag]);
}
我一直试图做的只是在屏幕上添加5个按钮。理想情况下,我想创建按钮,将它们放在一个数组(NSMutableArray)中,以便我以后可以操作它们,然后将tiles
抛出到MainViewController。但是,如果没有瓷砖对象,我甚至都没有将按钮送到控制器。
编辑:我想我会补充说,它们属于一个数组并不重要,重要的是我以后可以与它们进行交互,也就是说,它会有动画和文字变化等等。然而,最初的问题是它们没有在控制器上显示
答案 0 :(得分:3)
您的代码实际上非常有效,但是您无法说出因为:
为了显而易见,只需将按钮放大并更改背景颜色:
-(void)initTiles
{
//tiles = [[NSMutableArray alloc] initWithCapacity:5];
for (int count = 0; count < 5; count++)
{ //I used tiles.count here, but that fails
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(count*50+10, 50, 50, 50)];
[b setTitle:[NSString stringWithFormat:@"%i",count+1] forState:UIControlStateNormal];
[b setTag:count];
[b setHidden:NO];
[b addTarget:self action:@selector(tilePressed:) forControlEvents:UIControlEventTouchUpInside];
[b setBackgroundColor:[UIColor purpleColor]];
[self.view addSubview:b];
}
}
现在,只要将它们添加到数组中:
-(void)initTiles
{
self.tiles = [[NSMutableArray alloc] initWithCapacity:5];
for (int count = 0; count < 5; count++)
{ //I used tiles.count here, but that fails
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(count*50+10, 50, 50, 50)];
[b setTitle:[NSString stringWithFormat:@"%i",count+1] forState:UIControlStateNormal];
[b setTag:count];
[b setHidden:NO];
[b addTarget:self action:@selector(tilePressed:) forControlEvents:UIControlEventTouchUpInside];
[b setBackgroundColor:[UIColor purpleColor]];
[self.tiles addObject:b];
[self.view addSubview:b];
}
}
然后,您可以使用数组访问按钮!