Calculate Uitableviewcell Height to Fit String

Calculate UITableViewCell height to fit string

Use the following code to calculate and to set the height for cell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Define `veryverySmallTitleFont`
// Define `descLabel`

NSString *ourText = @"Your string data from array";
UIFont *font = [UIFont fontWithName:@"Verdana" size:veryverySmallTitleFont];
font = [font fontWithSize:veryverySmallTitleFont];

CGSize constraintSize = CGSizeMake(descLabel.frame.size.width, 1000);
CGSize labelSize = [ourText sizeWithFont:font
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];

return labelSize.height;
}

Change the UITableViewCell Height According to Amount of Text

Based on the code you have provided, I think you are increasing only the cell height and not the cell.textLabel's height.

Ideally, you should set the frame size of cell.textLabel and the cell for you to see the full text in the cell.

A neat way to see whats wrong with a view in terms of size, is to color it different than the background (try setting cell.textLabel background to yellow) and see if the height is actually being set.

Here's how it should be

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];

NSString *cellText = @"Go get some text for your cell.";
UIFont *cellFont = cell.textLabel.font;
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
cell.textlabel.frame.size = labelSize;
cell.text = cellText;
}

Hope this helps!

update: This is quite an old answer, and many lines in this answer may be deprecated.

getting the height of the custom cell in UITableViewCell

You can use Autolayout for the same and get free from all the coding part. Just set the constraint of the inner view in association with the cell and then right the following code.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell:ChatSenderTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "ChatSenderTableViewCell", for: indexPath) as? ChatSenderTableViewCell)!

cell.LabelChatMessage.text = "Your Message"
cell.LabelChatMessage.numberOfLines = 0
cell.LabelChatMessage.sizeToFit()

return cell

}

I am using a custom cell name ChatSenderTableViewCell to create a bubble like effect containing a label for messages send or receive.

How to calculate height of custom UITableViewCell by using UILabel's content

Implement your heightForRowAtIndexPath like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *text = [dataArray objectAtIndex:indexPath.row]; //your data string

CGSize constraint = CGSizeMake(yourLabel.frame.size.width, 2000.0f);
CGSize size;

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:yourLabel.font}
context:context].size;

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

return size.height;
}

Automatically grow static table view cell height to fit label content height

From personal experience getting UITableCells to grow correctly is one of the most annoying things in iOS. The biggest gotcha is normally the constraints. If they are not perfect than the cell won't grow.

The key is to be able to draw a straight line from the top of the cell content view to the bottom of the content view. so from your example constants should look something like the following.

topView.top == contentView.top
label.top == topView.top
label.bottom == topView.bottom
topView.bottom == bottomView.top
bottomView.height == 40
bottomView.bottom == contentView.bottom

Without having that straight line the layout can't determine the correct height for the label to display all of the content.

So a rather simple version of what you are looking for in a new sample project:

class ViewController: UITableViewController {
@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 80.0

label.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}

With the same layout:
Layout of Table Cell

Results in the following display in the simulator.
Result Image

How to set UITextView's height dynamically in UITableViewCell based on string size?

When using Auto-Layout for dynamically sizing cells, you don't really need to implement sizeThatFits(...). If the constraints are setup correctly, then you only need to disable the scrolling of the UITextView.

From code:

yourTextView.scrollEnabled = false

From IB:

Select your Text View and open Attributes inspector, then

Sample Image



Related Topics



Leave a reply



Submit