Jasper
Jasper

Reputation: 7107

Adding UIButton to subview not working

I'm trying to add 16 UIButton in code to a subview of my main view:

internView = [[UIView alloc] initWithFrame:CGRectMake(16, 16, (self.view.frame.size.width - 16), (self.view.frame.size.height - 16) - 60)];
internView.backgroundColor = [UIColor whiteColor];


for (int rij = 0; rij < 4; rij++) //4 rows
{
    for (int kolom = 0; kolom < 4; kolom++) //4 colomns
    {

        CGFloat x = (((width + spacing) * kolom) + spacing);
        CGFloat y = (((height + spacing) * rij) + spacing);
        int tag = ((4 * rij) + kolom);


        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor blackColor];

        [button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[projects objectAtIndex:tag]thumbnailImage]]]] forState:UIControlStateNormal];

        [button addTarget:self action:@selector(getDetail:) forControlEvents:UIControlStateNormal];

        button.tag = tag;

        NSLog(@"%i",button.tag);

        [internView addSubview:button];

    }
}

[self.view addSubview:internView];

The subview 'internview' is visible (as i made it white background) on the main view but the buttons aren't visible.

Also my log shows the tag of the button which goes from 0..15, so I know they are being made but simple aren't added to the subview 'internview'

Can't really see what I'm missing or doing wrong here..

Upvotes: 0

Views: 3071

Answers (1)

beryllium
beryllium

Reputation: 29767

Change your code to :

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(x, y, width, height);

In your version you have:

  1. Memory leak because you have created buttons two times
  2. [UIButton buttonWithType:UIButtonTypeCustom]; returns new button with CGRectZero frame

Upvotes: 7

Related Questions