Bangalore Bangalore - 5 months ago 17
iOS Question

Dynamically create UILabels in UITableView from a json in iOS?

Iam trying to create this design enter image description here

from following json

details = (
(
{
subtitle = "One";
title = 1;
},
{
subtitle = "two";
title = "2";
},
{
subtitle = "three";
title = "3";
}
),
(
{
subtitle = "one_two";
title = "1_2";
},
{
subtitle = "two_two";
title = "2_2";
}
)
);


I have tried following code and its not showing any UILables

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] ;

NSUInteger row = [indexPath row];
int i = 0;
NSUInteger nLabels = [[mainArray objectAtIndex:indexPath.row ] count];
UILabel *label;
float x =self.tableView.frame.size.width/nLabels;

for (i = 0; i < nLabels; i++) {
label = [[UILabel alloc] initWithFrame:CGRectMake(10 + (i * x), cell.frame.origin.y, 40, cell.frame.size.height)] ; //replace 40 with desired label width
label.textColor = [UIColor grayColor];
label.backgroundColor = [UIColor clearColor];
// set the label text here
label.text=@"treWT";
[label setNumberOfLines:0];
[label setAdjustsFontSizeToFitWidth:YES];
[cell.contentView addSubview:label];

}
}

return cell;
}


Now i can see simulator in this way
enter image description here

still its not aligned
Pls help me

Answer

Try below code for label alignment :

    NSUInteger row = [indexPath row];
    int i = 0;
    NSUInteger nLabels = [[mainArray objectAtIndex:indexPath.row ] count];
    UILabel *label;
    float w =self.tableView.frame.size.width/nLabels;
    float x = 0; 

    for (i = 0; i < nLabels; i++) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(x, cell.frame.origin.y, w, cell.frame.size.height)] ; //replace 40 with desired label width
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        // set the label text here
        label.text=@"treWT";
        [label setNumberOfLines:0];
        [label setAdjustsFontSizeToFitWidth:YES];
        label.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:label];
         x += w;
    }
Comments