Pavithra Selvaraj
Pavithra Selvaraj

Reputation: 85

How to programatically create the buttons horizontally within a View in ios

I dono how to align the buttons horizontally(x axis) if I use this code the images are getting placed over another button without spacing.

Here is the code I have used.Thanks in advance for the answers.

NSArray *arr1 = [pJson1 objectForKey:@"Response"];
        for (int i=0; i<arr1.count; i++)
    {
        int yval;
        int x ;
        btnNew = [[UIButton alloc]initWithFrame:CGRectMake(0,yval, 50, 30)];
        btnNew.backgroundColor = [UIColor blackColor];
        NSString *str = [NSString stringWithFormat:@"%@",[[arr1 objectAtIndex:i]objectForKey:@"name"]];
        [btnNew setTitle:str forState:UIControlStateNormal];
        btnNew.center = CGPointMake(160.0, 240.0);
        CGSize stringsize = [str sizeWithFont:[UIFont systemFontOfSize:14]];
        //or whatever font you're using
        [btnNew setFrame:CGRectMake(5,yval+10,100, 20)];
        btnNew.tag = i;
        [self.categoryView addSubview:btnNew];
        x += 2;
        yval +=10;
    }

Upvotes: 0

Views: 70

Answers (1)

Dharmesh Dhorajiya
Dharmesh Dhorajiya

Reputation: 3984

Try this code :

    NSArray *arr1 = [pJson1 objectForKey:@"Response"];
    int x ;
    for (int i=0; i<arr1.count; i++)
    {

       UIButton *btnNew = [[UIButton alloc]initWithFrame:CGRectMake(x,20, 50, 30)];
        btnNew.backgroundColor = [UIColor blackColor];
        NSString *str = [NSString stringWithFormat:@"%@",[[arr1 objectAtIndex:i]objectForKey:@"name"]];
        [btnNew setTitle:str forState:UIControlStateNormal];
        CGSize stringsize = [str sizeWithFont:[UIFont systemFontOfSize:14]];
        //or whatever font you're using
        btnNew.tag = i;
        [self.categoryView addSubview:btnNew];
        x += 55;
    }

Upvotes: 1

Related Questions