Dynamically increase height of UILabel & TableView Cell?
Asked Answered
M

8

19

I have a UITableView in which i am displaying a custom cell.I my cell i have two label & one view as below in picture.

enter image description here

I have given constraint of left view like this

Item label constraints

enter image description here

center view constraints

enter image description here

right view constarints

enter image description here
I am using a bean class to store data for two labels & add that bean object into one array.I am using below code in heightForRowAtIndexPath.

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

    // Calculate a height based on a cell
    if(!self.customCell) {
        self.customCell = [self.tableView dequeueReusableCellWithIdentifier:@"thirdcell"];
    }

    // Configure the cell
    Instrument *inst=[arr_instSpecs objectAtIndex:indexPath.row];
    self.customCell.label_item.text=inst.item;
    self.customCell.label_desc.text=inst.desc;


    // Layout the cell

    [self.customCell layoutIfNeeded];

    // Get the height for the cell

    CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // Padding of 1 point (cell separator)
    CGFloat separatorHeight = 1;

    return height + separatorHeight;
}

Problem is neither height of label is increasing nor of table view cell.I have explained everything. I want to make size of label increase when there is increase in label's text & also when label size increase then height of cell must increase.

Monticule answered 17/3, 2016 at 5:31 Comment(6)
Your question is not clear about what you want to achieve. Still from your code you are returning height by calculating instead return UITableViewAutomaticDimension.Monicamonie
There are tons of answer about the similar scenorio on SO, this is one of #19215699Monicamonie
I have explained everything.I want to make size of label increase when there is increase in label's text & also when label size increase then height of cell must increase.Monticule
Is 'Item' and 'Description' both kind of UILabel class? And is there only two labels in your cell?Monicamonie
You have mentioned that you have one view also in the cell, where it is? And whats its use?Monicamonie
green line is vertical view i have added it to make separator between two labelsMonticule
M
39

First of all you should not calculate height manually in auto layout environment. Just set both labels TopSpace and BottomSpace to cell's contentView and make sure you set both labels NumberOfLines to 0 and LineBreakMode to WordWrap.

And the other constraint are as below,

ItemLabel:

enter image description here

SeparatorView:

enter image description here

DescriptionLabel:

enter image description here

And add the delegates for height as below,

#pragma mark - UITableView Delegates
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 44.0;
}

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

    return UITableViewAutomaticDimension;
}

You should get the output as below,

enter image description here

Hope this would help you.

Monicamonie answered 17/3, 2016 at 8:3 Comment(0)
T
7

To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.

  • Assign and implement tableview dataSource and delegate
  • Assign UITableViewAutomaticDimension to rowHeight & estimatedRowHeight
  • Implement delegate/dataSource methods (i.e. heightForRowAt and return a value UITableViewAutomaticDimension to it)

-

Objective C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

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

    return UITableViewAutomaticDimension;
}

Swift:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

   // Set automatic dimensions for row height
    // Swift 4.2 onwards
    table.rowHeight = UITableView.automaticDimension
    table.estimatedRowHeight = UITableView.automaticDimension


    // Swift 4.1 and below
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension

}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Swift 4.2 onwards
    return UITableView.automaticDimension

    // Swift 4.1 and below
    return UITableViewAutomaticDimension
}

For label instance in UITableviewCell

  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

enter image description here

Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.

Tammeratammi answered 27/7, 2017 at 17:31 Comment(1)
I have old xibs with mask constraints...do you have any idea how to do this for xibs with mask constraints?Carberry
C
4

You need to define maximum estimated Height when view is loading

tblObject.estimatedRowHeight = 300;
tblObject.rowHeight = UITableViewAutomaticDimension;
Crotch answered 17/3, 2016 at 6:58 Comment(0)
T
4

This is how I worked out.

1) Set no. of lines to 0.

2) Set LineBreakage.

enter image description here

3) Add Constraints.

enter image description here

4) Change vertical content hugging priority.

enter image description here

5) On ViewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()

    self.sampleTableView.estimatedRowHeight = 600.0;
    self.sampleTableView.rowHeight = UITableViewAutomaticDimension;

    self.sampleTableView.setNeedsLayout()
    self.sampleTableView.layoutIfNeeded()
}

6) On TableView Custom Cell:

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    sizeToFit()
    layoutIfNeeded()
}
Thematic answered 20/10, 2016 at 9:1 Comment(0)
R
2

Give your label constraint as top to Cell , Bottom to cell and keep your Leading and trailing constraint as it is. In

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView
    estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

by using UITableViewAutomaticDimension will grow your tableview cell height according to your label's content and most important point is , select your label then go to Identity Inspector and in number of lines , write 0

Retral answered 17/3, 2016 at 5:38 Comment(0)
A
1

Swift 3 / Swift 4

Custom cell:

class CustomCell: UITableViewCell {

    @IBOutlet var messageLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        sizeToFit()
        layoutIfNeeded()

    }

}

viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()        

    self.tableView.estimatedRowHeight = 80
    self.tableView.rowHeight = UITableViewAutomaticDimension

}

And cellForRowAtIndexPath:

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

     let cell : CustomCell = tableView.dequeueReusableCell(withIdentifier: "yourcellIdentifier", for: indexPath) as! CustomCell
     cell.messageLabel.text = exampleContent[indexPath.row]
     cell.messageLabel.sizeToFit()
     cell.messageLabel.layoutIfNeeded()
     return cell

}

Anaplastic answered 19/5, 2018 at 5:29 Comment(0)
C
1

Swift 4.2

For the Basic or Subtitle type of cell, first in viewDidLoad you do this:

    self.tableView.estimatedRowHeight = 44 // This is the default cell height
    self.tableView.rowHeight = UITableView.automaticDimension

enter image description here

Then select the Title and set its number of lines to 0. Now the row will adjust its height based on the Title text. You don't need to do anything else.

enter image description here

Same goes for your Custom cell types. Make sure the Label which you use in your custom cell is set for 0 lines as well.

Crisis answered 21/1, 2019 at 0:51 Comment(0)
N
0

I was working on someone else's code and none of the given answers worked for me. The constraints were correct. Changing the "Desired Width" of label to automatic, in the storyboard did the job for me me. To do this, uncheck the "Explicit" checkmark in the Size Inspector for the label.

It should be like this

Numberless answered 1/2, 2021 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.