objective c - How to calculate number lines required for text -


i know going stupid daft simple question i'm going round in circles.

i have several strings want displaying in uitableview. of these strings long. have asked how calculate cell height, , choose following answer:

- (cgfloat)cellheightforrowatindexpath:(nsindexpath *)indexpath {     nsstring *cellstring = <your model object>;      nsdictionary *attributes = @{ nsfontattributename : [uifont systemfontofsize:16.0f] };     nsmutableattributedstring *attributedstring = [[nsmutableattributedstring alloc]                                                initwithstring: cellstring                                                attributes:attributes];      cgfloat width = self.tableview.frame.size.width - 32.0f;      cgrect frame = [attributedstring boundingrectwithsize:cgsizemake(width, maxfloat) options:nsstringdrawinguseslinefragmentorigin context:nil];      // add padding height         cgfloat height = frame.size.height + 16.0f;      return ceil(height); }  - (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath {     return [self cellheightforrowatindexpath:indexpath]; } 

how can number of lines required in uitableview display strings.

the best way calculate cell height use prototype cell calculating height.

add property interface extension:

@interface tableviewcontroller ()  @property (nonatomic, strong) tableviewcell *prototypecell;  @end 

then lazily load it:

- (tableviewcell *)prototypecell {   if (!_prototypecell)   {     _prototypecell = [[tableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:@"prototype"];   }   return _prototypecell; } 

change -[tableview:cellforrowatindexpath:] method use -[configurecell:forrowatindexpath:] type pattern:

-(uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {     tableviewcell *cell = [tableview dequeuereusablecellwithidentifier:@"cellid" forindexpath:indexpath];      [self configurecell:cell forrowatindexpath:indexpath];      return cell; }  -(void)configurecell:(tableviewcell *)cell forrowatindexpath:(nsindexpath *)indexpath {     // set cell model } 

now use method setup prototype , use height of -[tableview:heightforrowatindexpath:]:

-(cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath {   [self configurecell:self.prototypecell forrowatindexpath:indexpath];   [self.prototypecell layoutifneeded];    cgsize size = [self.prototypecell.contentview systemlayoutsizefittingsize:uilayoutfittingcompressedsize];   return ceil(size.height); } 

Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -