objective c - Dynamically size uitableViewCell according to UILabel (With paragraph spacing) -


i have uitableview populated text , images json file. tableview cell sizing correctly "posts" not contain many line breaks in text cannot calculate correct height "posts" 4 or 5 line breaks.

code getting height:

-(float)height :(nsmutableattributedstring*)string {   nsstring *stringtosize = [nsstring stringwithformat:@"%@", string];    cgsize constraint = cgsizemake(label_width - (label_margin *2), 2000.f);    cgsize size = [stringtosize sizewithfont:[uifont systemfontofsize:font_size] constrainedtosize:contraint linebreakmode:nslinebreakbywordwrapping];    return size.height; } 

how calculate correct size while allowing line breaks , white space?

edit

the rest of method,

inside of tableview cellforrow:

-(uitableviewcell*)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { nsstring *row = [nsstring stringwithformat:@"%i", indexpath.row];  float posttextheight = [self height:posttext];  nsstring *height = [nsstring stringwithformat:@"%f", heightofposttext + 70];  [_cellsizes setobject:height forkey:row]; } 

and height of table cell:

-(cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath { nsstring *imageheightstring = [nsstring stringwithformat:@"%@", [_cellsizes objectforkey:indexpath.row]];  float heightofcell = [imageheightstring floatvalue];   if (heightofcell == 0) {      return 217; };  return heightofcell + 5; } 

better u need calculate height first, don't include height calculation part in method:

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath 

better calculate in method:

- (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath  

since u getting data json easy u calculate in "heightforrowatindexpath" method.

follwing code give example calculate height of text change ur requirement. hopee helps u :)

// using array  - (void)viewdidload {    [super viewdidload];     // additional setup after loading view, typically nib.     uifont *labelfont = [uifont fontwithname:@"noteworthy-bold" size:20];    nsdictionary *arialdict = [nsdictionary dictionarywithobject:labelfont forkey:nsfontattributename];     nsmutableattributedstring *message = [[nsmutableattributedstring alloc] initwithstring:@"this sample example of how calculate dynamic height tableview cell of around 7 8 lines. need set height of string first, not seems calculated in cellforrowatindexpath method." attributes:arialdict];     array = [nsmutablearray arraywithobjects:message, nil];    nsmutableattributedstring *message_1 = [[nsmutableattributedstring alloc] initwithstring:@"you need set height of string first, not seems calculated in cellforrowatindexpath method." attributes:arialdict];   [array addobject:message_1];    }   - (nsinteger)numberofsectionsintableview:(uitableview *)tableview  {      return 2;  }   - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section  {      return 2;  }    - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {    uitableviewcell *cell = [self.atableview dequeuereusablecellwithidentifier:@"cell"];    if(cell == nil)     {        cell = [[uitableviewcell alloc]initwithstyle:uitableviewcellstyledefault reuseidentifier:@"cell"];      }       //dont include height calculation part hear, becz heights set cell      [cell.textlabel sizetofit];     cell.textlabel.attributedtext = [array objectatindex:indexpath.row]; // dont calculate height hear called after "heightforrowatindexpath" method     cell.textlabel.numberoflines = 8;     return cell;  }    // put ur height calculation method took hardcoded values change :)   -(float)height :(nsmutableattributedstring*)string  {     /*       nsstring *stringtosize = [nsstring stringwithformat:@"%@", string];    // cgsize constraint = cgsizemake(label_width - (label_margin *2), 2000.f);      cgsize maxsize = cgsizemake(280, maxfloat);//set max height //set constant width, hear maxfloat gives maximum height       cgsize size = [stringtosize sizewithfont:[uifont systemfontofsize:20.0f] constrainedtosize:maxsize linebreakmode:nslinebreakbywordwrapping]; return size.height; //finally u correct height     */      //commenting above code because "sizewithfont: constrainedtosize:maxsize: linebreakmode: " has been deprecated avoid above code use below      nsattributedstring *attributedtext = string;     cgrect rect = [attributedtext boundingrectwithsize:(cgsize){225, maxfloat}                            options:nsstringdrawinguseslinefragmentorigin                               context:nil];//you need specify width, height calculated     cgsize requiredsize = rect.size;     return requiredsize.height; //finally u return height }   - (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath  {      //whatever height u need calculate calculate hear          cgfloat heightofcell = [self height:[array objectatindex:indexpath.row]];      nslog(@"%f",heightofcell);      return heightofcell;  } 

hope helps u :)

for swift version

class viewcontroller: uiviewcontroller,uitableviewdatasource,uitableviewdelegate  {  var messagearray:[string] = [] //array holde response form son example  override func viewdidload() {     super.viewdidload()     // additional setup after loading view, typically nib.     messagearray = ["one of interesting features of newsstand once asset downloading has started continue if application suspended (that is: not running still in memory) or terminated. of course during while app suspended not receive status update woken in background",                     "in case app has been terminated while downloading in progress, situation different. infact in event of finished downloading app can not woken , connection delegate finish download method called, when app terminated app delegate object doesn’t exist anymore. in such case system relaunch app in background.",                      " if defined, key contain array of asset identifiers caused launch. tests doesn’t seem check required if reconnect pending downloading explained in next paragraph.",                     ] }  func numberofsectionsintableview(tableview: uitableview) -> int {     return 1; }  func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {     return messagearray.count; }  func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {     var cell:uitableviewcell? = tableview.dequeuereusablecellwithidentifier("cell") as? uitableviewcell;     if(cell == nil)     {         cell = uitableviewcell(style:uitableviewcellstyle.default, reuseidentifier: "cell")         cell?.selectionstyle = uitableviewcellselectionstyle.none     }     cell?.textlabel.font = uifont.systemfontofsize(15.0)     cell?.textlabel.sizetofit()     cell?.textlabel.text = messagearray[indexpath.row]     cell?.textlabel.numberoflines = 0     return cell!; }  func tableview(tableview: uitableview, heightforrowatindexpath indexpath: nsindexpath) -> cgfloat {     var height:cgfloat = self.calculateheightforstring(messagearray[indexpath.row])     return height + 70.0 }  func calculateheightforstring(instring:string) -> cgfloat {     var messagestring = instring     var attributes = [uifont(): uifont.systemfontofsize(15.0)]     var attrstring:nsattributedstring? = nsattributedstring(string: messagestring, attributes: attributes)     var rect:cgrect = attrstring!.boundingrectwithsize(cgsizemake(300.0,cgfloat.max), options: nsstringdrawingoptions.useslinefragmentorigin, context:nil )     var requredsize:cgrect = rect     return requredsize.height  //to include button's in tableview   } } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -