Reputation: 409
I have a table which is going to show comments. These can of course be of different length which means each cell needs specific height.
When I do tables I usually have a custom cell where I define the frame size with CGRectMake for each label. With the comment text label the frame can not have the same height all the time.
What I did was implement some code in:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
which calculate the needed size for the comment text frame:
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont systemFontOfSize:13];
gettingSizeLabel.text = cLine.commentTxt;
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(commentsListTableView.contentSize.width-15, 9999);
CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
CGRect frame= CGRectMake(15, 25, expectSize.width, expectSize.height);
cell.CommentLabel.frame = frame;
Then in:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
I put the same code plus a spacer for some other labels which always have the same height:
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont systemFontOfSize:13];
gettingSizeLabel.text = cLine.commentTxt;
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(commentsListTableView.contentSize.width-15, 9999);
CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
return expectSize.height+30;
It looks to be working, but when I scroll in the table I can see that sometimes it seems to be messing up the calculations and text overflows to the next cells. The weird thing is, it seems to be the same cells which mess up every time.
Should I be doing this in a different way?
Upvotes: 2
Views: 464
Reputation: 409
I found the problem with the original solution.
The reason it messed up the rendering, was because I only executed this code when the cell was nil:
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont systemFontOfSize:13];
gettingSizeLabel.text = cLine.commentTxt;
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(commentsListTableView.contentSize.width-15, 9999);
CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
CGRect frame= CGRectMake(15, 25, expectSize.width, expectSize.height);
cell.CommentLabel.frame = frame;
Once I changed it to be executed on the cell every time, everything works and looks correct. I will keep using this solution because it is not dependent on PureLayout.
Upvotes: 1