Search code examples
iosuitableviewsizelabelcell

ios: fit cell with label in it to the size of the label


I'm having a tableview and loading data width a json Array. What I'm doing is, I make two UILabel which i put in each table view cell. This is working and with[label sizeToFit];. My problem is now to set the size of the cell which is holding those two labels. I tried to set [cell sizeToFit]; but this isn't working. Does anyone could help me to solve this? Here is the code:

NSString * titel = [[json_Array objectAtIndex:indexPath.row ] objectForKey:@"maintitel"];
NSString * datum = [[json_Array objectAtIndex:indexPath.row] objectForKey:@"datum"];

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-mm-dd"];
NSDate *date = [dateFormat dateFromString:datum];

// Convert date object to desired output format
[dateFormat setDateFormat:@"dd.mm.yy"];
NSString * dateStr = [dateFormat stringFromDate:date];
NSString * datum1 = [dateStr description];

UILabel *label =  [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 80, 50)];
label.text = datum1;

UILabel *label1 =  [[UILabel alloc] initWithFrame: CGRectMake(80, 0, 245, 50)];
label1.text = titel;

label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.userInteractionEnabled = NO;

label1.numberOfLines = 0;
label1.lineBreakMode = UILineBreakModeWordWrap;
label1.userInteractionEnabled = NO;

[label sizeToFit];
[label1 sizeToFit];

[cell.contentView addSubview:label];
[cell.contentView addSubview:label1];

My second question is because I'm almost new in iOS Developing but have already done some android projects, Is this the best way to make a screen looking like I want?


Solution

  • - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
    {
    
    NSString * datum = [[json_Array objectAtIndex:indexPath.row] objectForKey:@"datum"];
    
        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [datum sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    
    
        CGFloat height = MAX(size.height, 77.0f);
    
        return height + (CELL_CONTENT_MARGIN * 2);
    }
    

    Consider a string wich is having max height then fit height for the cell .I considered datum string you implement according to your requirement