Custom heightForRowAtIndexPath (CGSize sizeWithFont) with NSAttributedString iOS

I have a table view where the height of the cells is determined dynamically depending on the text it represents.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { //getting my text for this cell, the row etc ... ... //here is the part interesting us NSAttributedString* theText = [myTextForThisCell objectAtIndex:indexPath.row]; NSInteger labelWidth = self.tableView.bounds.size.width-HORIZONTAL_CELL_PADDING; CGSize textSize = [theText sizeWithFont:[UIFont systemFontOfSize:customFontSize] constrainedToSize:CGSizeMake(labelWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; return textSize.height+VERTICAL_CELL_PADDING; } 

OK, now my problem. The table view is the result of a search action that, after scanning the plist file, shows the rows containing the given row.

So far it has been. But now with iOS 6 and NSAttributedString, which make it easy to highlight the bold part of the lines, I decided to boldly search for the search word.

It works, it dares the words I want, but now I can no longer calculate the height of the cell, since sizeWithFont is requesting an NSString. And since the offset takes a wider width, I can't just calculate the height of a cell with a row without attributes.

I'm just stuck here.

Can anybody help me?

+4
source share
1 answer

Actually, I just needed to read Apple's NSAttributedText documentation.

In my case, I have to replace the last two lines of code with

 CGRect rectSize = [theText boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:NULL]; return rectSize.size.height+VERTICAL_CELL_PADDING; 

FOLLOW UP iOS 7

I am trying to make this work in iOS7 with attributed text.

Apple documentation says

In iOS 7 and later, this method returns fractional sizes (in the size of the components returned by CGRect); use the return size by the size of the views you should use to increase its value to the nearest higher integer using the ceil function.

Which way obviously doesn't work for me! For me, the solution was to add +1 to the ceiling height. This is probably Apple's mistake, but now everything works for me like in iOS6.

 CGRect rectSize = [theAttributedText boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:NULL]; return ceil(rectSize.size.height) + 1 + VERTICAL_CELL_PADDING; 
+23
source

Source: https://habr.com/ru/post/1444088/


All Articles