ios - UITableView Row Height Based on Cell contents -
i have looked @ several questions asking adjust row height based on cell content. in case, have 10 labels in 1 cell , each label has fixed width. labels must wrap text if not fit label width. row height depends on 10 label's text content. means have calculate height of every label given text , take maximum height amongst labels row height. have rows. looks me insufficient solution. there better solution?
thanks,
jignesh
the uitableview
requires implement heightforrowatindexpath
in order have custom height table cell. because uitableview
calculates total height of table each time data reloaded. cache row-height calculations if data static.
in case recommend creating data model class represents 10 label's worth of text , provide helper function on data model class can call in heightforrowatindexpath
. helper function encapsulate row height calculations perhaps this:
let's have data model class represents data in rows:
@interface mydatamodelclass : nsobject @property (strong, nonatomic) nsstring *label1text; @property (strong, nonatomic) nsstring *label2text; // ... etc - (cgfloat)calculatelabelheight; @end
then calculatelabelheight
method might (this pseudo code, obviously):
- (cgfloat)calculatelabelheight { cgfloat totalheight = 0.0; // loop through label texts calculating variable sized height each // , adding padding in between: cgsize variablesize1 = [self.label1text sizewithfont:[uifont systemfontofsize:12.0] constrainedtosize:cgsizemake(300, 400) linebreakmode:nslinebreakbywordwrapping]; cgsize variablesize2 = [self.label2text sizewithfont:[uifont systemfontofsize:12.0] constrainedtosize:cgsizemake(300, 400) linebreakmode:nslinebreakbywordwrapping]; totalheight = variablesize1 + padding + variablesize2 + padding; // , on labels. return totalheight; }
then in heightforrowatindexpath
can this:
- (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath mydatamodelclass *modelobject = [self.data objectatindex:indexpath.row]; // assuming model object's label text properties have been set can this: return modelobject.calculatelabelheight; }
it occurred me 1 label might have long string in causing wrap , possibly overlay second label. may want add method uitableviewcell
subclass called repositionlabels
or after know each label text's height.
unfortunately, think way calculate height cell. see s.o. post more info:
Comments
Post a Comment