6

I've been trying to do a dynamic cell with label using swift to support IOS7 in heightForRowAtIndexPath but i only find objective-c code, is it possible to somebody else to help me rewriting this code into swift ?

 // Fetch yourText for this row from your data source..
    NSString *yourText = [yourArray objectAtIndex:indexPath.row];

    CGSize lableWidth = CGSizeMake(300, CGFLOAT_MAX); // 300 is fixed width of label. You can change this value
    CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping]; // You can put your desire font

    // Here, you will have to use this requiredSize and based on that, adjust height of your cell. I have added 10 on total required height of label and it will have 5 pixels of padding on top and bottom. You can change this too.
    int calculatedHeight = requiredSize.height+10;
    return (float)calculatedHeight;

exactly this statement (how to convert it to swift) :

CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:19] constrainedToSize:lableWidth lineBreakMode:NSLineBreakByWordWrapping]

i tried converting it to (but it doesn't work as the original objective-c ) :

 var requiredSize: CGSize = originalString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(19.0)])
AaoIi
  • 7,995
  • 6
  • 40
  • 81
  • Here is best example for that just go thru it.http://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift – Nimit Parekh May 04 '15 at 13:31
  • Follow this link : http://stackoverflow.com/questions/9827126/change-the-uitableviewcell-height-according-to-amount-of-text/42111135#42111135> – Rubaiyat Jahan Mumu Feb 08 '17 at 11:12

1 Answers1

6

Maybe it's possible to do it without the UILabel but this works just fine.

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 10000))
label.text = someText
label.numberOfLines = 100
label.font = UIFont(name: "Times New Roman", size: 19.0)
label.sizeToFit()
return label.frame.height + 10
Stefan Salatic
  • 4,273
  • 3
  • 20
  • 30