Objective-C:以编程方式创建UITableViewCell高度问题?

时间:2016-12-02 08:41:10

标签: ios objective-c uitableview constraint-programming

如何根据来自响应的内容

在运行时调整UITableViewCell高度

这是我的代码:

·H

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>    
@end

的.m

import "ViewController.h"
import "CustomCellTableViewCell.h"

static NSString *cellIdentifier = @"cellIdentifier";


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self cofigureTableview];
}

-(void)cofigureTableview
{
    self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
      return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    CustomCellTableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:cellIdentifier];
    cell = [[CustomCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    [self setUpCell:cell atIndexPath:indexPath];

    return cell;
}

- (void)setUpCell:(CustomCellTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
     if (cell != nil)
     {
        UILabel *averageRatingLabel = [[UILabel alloc]init];
        averageRatingLabel.text = @"Average Rate";
        averageRatingLabel.textAlignment = NSTextAlignmentLeft;
        averageRatingLabel.numberOfLines = 0;
        averageRatingLabel.lineBreakMode = NSLineBreakByWordWrapping;
        averageRatingLabel.textColor = [UIColor blackColor];
        averageRatingLabel.translatesAutoresizingMaskIntoConstraints = NO;
        averageRatingLabel.font = [UIFont systemFontOfSize:12];
        [cell.contentView addSubview:averageRatingLabel];

        /////
        UILabel *sortByLabel = [[UILabel alloc]init];
        sortByLabel.text = @"SORT BY Value:";
        sortByLabel.textAlignment = NSTextAlignmentLeft;
        sortByLabel.numberOfLines = 0;
        sortByLabel.lineBreakMode = NSLineBreakByWordWrapping;
        sortByLabel.textColor = [UIColor grayColor];
        sortByLabel.translatesAutoresizingMaskIntoConstraints = NO;
        sortByLabel.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:sortByLabel];


        UILabel *sortByLabel1 = [[UILabel alloc]init];
        sortByLabel1.text = @"I want to adjust the row height of a UITableView according to the cell in that row. I want to adjust the row height of a UITableView according to the cell in that row.I want to adjust the row height of a UITableView according to the cell in that row";

        sortByLabel1.textAlignment = NSTextAlignmentLeft;
        sortByLabel1.numberOfLines = 0;
        sortByLabel1.lineBreakMode = NSLineBreakByWordWrapping;
        sortByLabel1.textColor = [UIColor grayColor];
        sortByLabel1.translatesAutoresizingMaskIntoConstraints = NO;
        sortByLabel1.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:sortByLabel1];

        UILabel *sortByLabel2 = [[UILabel alloc]init];
        sortByLabel2.text = @"Is there any method to achieve this:";
        sortByLabel2.textAlignment = NSTextAlignmentLeft;
        sortByLabel2.numberOfLines = 0;
        sortByLabel2.lineBreakMode = NSLineBreakByWordWrapping;
        sortByLabel2.textColor = [UIColor grayColor];
        sortByLabel2.translatesAutoresizingMaskIntoConstraints = NO;
        sortByLabel2.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:sortByLabel2];

        UILabel *sortByLabel3 = [[UILabel alloc]init];
        sortByLabel3.text = @"This should work because tableView: cellForRowAtIndexPath:";
        sortByLabel3.textAlignment = NSTextAlignmentLeft;
        sortByLabel3.numberOfLines = 0;
        sortByLabel3.lineBreakMode = NSLineBreakByWordWrapping;
        sortByLabel3.textColor = [UIColor grayColor];
        sortByLabel3.translatesAutoresizingMaskIntoConstraints = NO;
        sortByLabel3.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:sortByLabel3];

        UILabel *sortByLabel4 = [[UILabel alloc]init];
        sortByLabel4.text = @"then in your tableView:  in your viewDidAppearthen in your tableView: cellForRowAtIndexPath: update this variable like your new height and then reload the [self.yourTable reloadData] in your viewDidAppearthen in your tableView: cellForRowAtIndexPath: update this variable like your new height and then reload the [self.yourTable reloadData] in your viewDidAppear:";
        sortByLabel4.textAlignment = NSTextAlignmentLeft;
        sortByLabel4.numberOfLines = 0;
        sortByLabel4.lineBreakMode = NSLineBreakByWordWrapping;
        sortByLabel4.textColor = [UIColor grayColor];
        sortByLabel4.translatesAutoresizingMaskIntoConstraints = NO;
        sortByLabel4.font = [UIFont systemFontOfSize:10];
        [cell.contentView addSubview:sortByLabel4];


        NSDictionary *viewDict1 = NSDictionaryOfVariableBindings(averageRatingLabel);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[averageRatingLabel]|" options:0 metrics:0 views:viewDict1]];
       [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[averageRatingLabel]" options:0 metrics:0 views:viewDict1]];

        NSDictionary *viewDict2 = NSDictionaryOfVariableBindings(sortByLabel,averageRatingLabel);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[sortByLabel]-5-|" options:0 metrics:0 views:viewDict2]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[averageRatingLabel]-5-[sortByLabel]" options:0 metrics:0 views:viewDict2]];

        NSDictionary *viewDict3 = NSDictionaryOfVariableBindings(sortByLabel,sortByLabel1);
       [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[sortByLabel1]-5-|" options:0 metrics:0 views:viewDict3]];
       [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sortByLabel]-5-[sortByLabel1]" options:0 metrics:0 views:viewDict3]];

        //
        NSDictionary *viewDict4 = NSDictionaryOfVariableBindings(sortByLabel1,sortByLabel2);
       [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[sortByLabel2]-5-|" options:0 metrics:0 views:viewDict4]];
       [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sortByLabel1]-5-[sortByLabel2]" options:0 metrics:0 views:viewDict4]];

        //
        NSDictionary *viewDict5 = NSDictionaryOfVariableBindings(sortByLabel2,sortByLabel3);


        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[sortByLabel3]-5-|" options:0 metrics:0 views:viewDict5]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sortByLabel2]-5-[sortByLabel3]" options:0 metrics:0 views:viewDict5]];

        //
        NSDictionary *viewDict6 = NSDictionaryOfVariableBindings(sortByLabel3,sortByLabel4);
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[sortByLabel4]-5-|" options:0 metrics:0 views:viewDict6]];
        [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sortByLabel3]-5-[sortByLabel4]" options:0 metrics:0 views:viewDict6]];

     }
}

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

    static CustomCellTableViewCell *cell = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    });
    [self setUpCell:cell atIndexPath:indexPath];

    return [self calculateHeightForConfiguredSizingCell:cell];

}

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell
{

    [sizingCell layoutIfNeeded];
    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}


- (void)didReceiveMemoryWarning
{

    [super didReceiveMemoryWarning];

}

@end

4 个答案:

答案 0 :(得分:0)

使用此代码根据内容大小自动调整单元格高度:

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

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

您也可以使用它:

self.tableView.estimatedRowHeight = 300.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

答案 1 :(得分:0)

对于内容的动态高度,首先需要计算内容大小,然后根据该高度计算高度,并将该高度传递给您的表格视图单元格高度,如下所示 -

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
    CGSize constraint = CGSizeMake(width , 20000.0f);
    CGSize title_size;
    float totalHeight;
    SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
    if ([text respondsToSelector:selector]) {                
        title_size = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{ NSFontAttributeName : font }
                                        context:nil].size;
        totalHeight = ceil(title_size.height); 
    } else {                
        title_size = [text sizeWithFont:font
                      constrainedToSize:constraint
                          lineBreakMode:NSLineBreakByWordWrapping];                
        totalHeight = title_size.height ;                
    }
    CGFloat height = MAX(totalHeight, 40.0f);
    return height;            
}

将此高度传递给表格视图单元格 -

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

答案 2 :(得分:0)

enter image description here

我的观点是这样的,但我不知道它的优先级是一个接一个,一个接一个,或者可能是UIButton的第一个或最后一个。没有什么能够根据服务器的响应来修复它。

答案 3 :(得分:-1)

使用下面的代码调整单元格高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch(indexPath.row){
   case:0
    return 100;
   break;

   case:1
    return 200;
   break;
    }
 }

根据案例调整你的细胞高度。

希望这会对你有所帮助。