iOS: Dynamic Height For UITableViewCell

一个人想着一个人 提交于 2019-11-29 15:11:12

Give your label constrains relative to the cell, top, bottom, left and right.

Than your cell size will grow with the content height.

also make your label multiline.(by setting Lines property to 0 in attribute inspector)

#pragma mark- Menu table Delegates 

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

    return UITableViewAutomaticDimension;
}

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

    return UITableViewAutomaticDimension;
}

I'm not quite sure what this sentence means (a screenshot would've helped):

"I need to change the height of cell Dynamically according to labelText Height"

So, you have a UITableViewCell, containing a UILabel, and want each cell in your table to have a height depending on that cell's label ?

Here's the code I use.

In my UITableViewCell class, I'll define a static function to measure, and return the height of my .xib file:

@implementation MikesTableViewCell

...

+(CGSize)preferredSize
{
    static NSValue *sizeBox = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // Assumption: The XIB file name matches this UIView subclass name.
        NSString* nibName = NSStringFromClass(self);
        UINib *nib = [UINib nibWithNibName:nibName bundle:nil];

        // Assumption: The XIB file only contains a single root UIView.
        UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];

        sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
    });
    return [sizeBox CGSizeValue];
}

@end

Then, in my UIViewController class, I'll tell my UITableView to use this cell, find out it's height.

@property (nonatomic) float rowHeight;

UINib *cellNib = [UINib nibWithNibName:@"MikesTableViewCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomerCell"];

rowHeight = [MikesTableViewCell preferredSize].height;

...

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

Again, this might not be exactly what you're looking for, but I hope this helps.

try this. it is so simple.

set this height in heightForRowAtIndexPath method

  float vendorNameHeight = [vendorNameLbl.text heigthWithWidth:width andFont:[UIFont fontWithName:@"Signika-Light" size:21.0]];

then

  UILabel*vendorNameLbl=[[UILabel alloc]initWithFrame:CGRectMake( 13, 11, 100, 22)];
  vendorNameLbl.numberOfLines = 0;
  [vendorNameLbl sizeToFitVertically];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!