0

我一直在开发一个应用程序,我在 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) 中,以便以后可以操作它们,然后将它们扔到tilesMainViewController。但我什至没有把按钮拿到控制器上没有瓷砖对象。

编辑:我想我会补充一下,它们是否属于一个数组并不重要,重要的是我可以稍后与它们交互,即倾斜会有动画和文本更改等。然而,最初的问题是,是他们没有显示在控制器上

4

1 回答 1

3

您的代码实际上可以完美运行,但是您无法确定,因为:

  • 按钮非常小,几乎无法使用
  • 按钮太小以至于文本标题不会显示
  • 背景颜色为 nil,因此默认为清除,这使得在这种情况下整个按钮不可见。

为了让它更明显,只需将按钮变大并更改背景颜色:

-(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];
    }
}

然后,您可以使用数组访问按钮!

于 2012-11-28T02:44:19.460 回答