动态增加UILabel和TableView单元格的高度?

19

我有一个UITableView,其中显示了一个自定义的单元格。 我的单元格中有两个标签和一个视图,如下面的图片所示。

enter image description here

我已经按照以下方式给左侧视图设定了约束

Item label constraints

enter image description here

center view constraints

enter image description here

right view constarints

enter image description here
我正在使用一个bean类来存储两个标签的数据,并将该bean对象添加到一个数组中。我在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;
}

问题是标签和表视图单元格的高度都没有增加。我已经解释了一切。当标签文本增加时,我想要使标签的尺寸增加,并且当标签尺寸增加时,单元格的高度也必须增加。


你的问题不清楚你想要实现什么。然而从你的代码来看,你正在通过计算返回高度,而不是使用UITableViewAutomaticDimension。 - Bharat Modi
在SO上有很多关于类似情况的答案,这是其中之一:https://dev59.com/IHfZa4cB1Zd3GeqPUaue - Bharat Modi
我已经解释了一切。当标签文本增加时,我想要标签的大小增加,并且当标签大小增加时,单元格的高度也必须增加。 - Dheeraj Kumar
“Item”和“Description”都是UILabel类的一种吗?而且你的单元格里只有两个标签吗? - Bharat Modi
你提到你在单元格中也有一个视图,它在哪里?它有什么用途? - Bharat Modi
绿色线是垂直视图,我已经添加它以在两个标签之间创建分隔符。 - Dheeraj Kumar
8个回答

39

首先,在自动布局环境中不应手动计算高度。只需将两个标签的TopSpace和BottomSpace设置为单元格的contentView,并确保将两个标签的NumberOfLines设置为0,LineBreakMode设置为WordWrap。

另外一些限制如下:

ItemLabel:

enter image description here

SeparatorView:

enter image description here

DescriptionLabel:

enter image description here

并添加以下内容来为高度设置委托:

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

    return 44.0;
}

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

    return UITableViewAutomaticDimension;
}

您应该能够得到以下输出结果:

enter image description here

希望这能对您有所帮助。


7

为了设置自动行高和估算行高,请按照以下步骤进行操作,以使单元格/行高布局的自动尺寸生效。

  • 分配并实现tableview dataSource和delegate
  • UITableViewAutomaticDimension分配给rowHeight和estimatedRowHeight
  • 实现代理/dataSource方法(例如heightForRowAt并返回一个值UITableViewAutomaticDimension

-

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
}

在UITableviewCell中使用标签:

  • 设置行数为0(并且换行模式为truncate tail)
  • 与其父视图/单元格容器相关联,设置所有约束条件(顶部、底部、右侧和左侧)。
  • 可选项:如果您想要标签覆盖的垂直区域最小化(即使没有数据),可以设置标签的最小高度。

enter image description here

注意:如果您有多个动态长度的标签(UIElements),应根据其内容大小调整它们:为您希望以更高优先级扩展/压缩的标签调整“Content Hugging and Compression Resistance Priority”。


我有旧的带有遮罩约束的xib...你有任何想法如何处理带有遮罩约束的xib吗? - jayant rawat

4
您需要在视图加载时定义最大预估高度。
tblObject.estimatedRowHeight = 300;
tblObject.rowHeight = UITableViewAutomaticDimension;

4

这就是我解决问题的方法。

1)将行数设置为0。

2)设置LineBreakage。

enter image description here

3)添加约束。

enter image description here

4) 更改垂直内容抱紧优先级。

enter image description here

5)在ViewDidLoad中:

override func viewDidLoad() {
    super.viewDidLoad()

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

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

6)在TableView自定义单元格上:

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

    sizeToFit()
    layoutIfNeeded()
}

2
将标签的约束条件设置为顶部对齐单元格,底部对齐单元格,并保持前导和尾随约束条件不变。 在

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

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

通过使用UITableViewAutomaticDimension,您的表格视图单元格高度将根据标签内容增加,最重要的是,选择您的标签,然后进入Identity Inspector,在行数中写0。

1
自定义单元格:

Swift 3 / Swift 4

自定义单元格:

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

}

而 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

}


1

Swift 4.2

对于基本单元格(Basic)或副标题单元格(Subtitle),在viewDidLoad中首先执行以下操作:

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

enter image description here

然后选择标题并将其行数设置为0。现在,该行将根据标题文本调整其高度。您不需要做任何其他操作。

enter image description here

同样适用于自定义单元格类型。确保您在自定义单元格中使用的标签也设置为0行。

0
我正在处理别人的代码,但是给出的答案都不适用于我。约束条件是正确的。 在Storyboard中将标签的“期望宽度”更改为自动,这对我很有帮助。要做到这一点,请在标签的“大小检查器”中取消“显式”复选框的选中状态。

It should be like this


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接