ios 动态增加 UILabel & TableView Cell 的高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36052361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically increase height of UILabel & TableView Cell?
提问by Dheeraj Kumar
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.
我有一个 UITableView,我在其中显示一个自定义单元格。我的单元格有两个标签和一个视图,如下图所示。
I have given constraint of left view like this
我已经给了这样的左视图约束
Item label constraints
项目标签约束
center view constraints
中心视图约束
right view constarints
右视约束
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.
我正在使用 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;
}
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.
问题既不是标签的高度增加,也不是表格视图单元格的高度。我已经解释了一切。当标签文本增加时,我想让标签的大小增加,并且当标签大小增加时,单元格的高度必须增加。
回答by Bharat Modi
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.
首先,您不应在自动布局环境中手动计算高度。只需将标签 TopSpace 和 BottomSpace 设置为单元格的 contentView,并确保将两个标签 NumberOfLines 设置为 0,将 LineBreakMode 设置为 WordWrap。
And the other constraint are as below,
另一个约束如下,
ItemLabel:
项目标签:
SeparatorView:
分隔符视图:
DescriptionLabel:
说明标签:
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,
你应该得到如下输出,
Hope this would help you.
希望这会帮助你。
回答by Krunal
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 valueUITableViewAutomaticDimension
to it)
- 分配和实现 tableview 数据源和委托
- 分配
UITableViewAutomaticDimension
给 rowHeight 和estimatedRowHeight - 实现委托/数据源方法(即
heightForRowAt
并UITableViewAutomaticDimension
为其返回值)
-
——
Objective C:
目标 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
对于 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.
- 设置行数 = 0(& 换行模式 = 截尾)
- 设置与其父视图/单元格容器相关的所有约束(顶部、底部、左侧)。
- 可选:设置标签的最小高度,如果你想要标签覆盖的最小垂直区域,即使没有数据。
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.
注意:如果您有多个具有动态长度的标签(UIElements),应根据其内容大小进行调整:为您希望以更高优先级展开/压缩的标签调整“内容拥抱和压缩阻力优先级”。
回答by Meera
You need to define maximum estimated Height when view is loading
您需要在加载视图时定义最大估计高度
tblObject.estimatedRowHeight = 300;
tblObject.rowHeight = UITableViewAutomaticDimension;
回答by A.G
This is how I worked out.
这就是我的工作方式。
1) Set no. of lines to 0.
1) 设置编号 行数为 0。
2) Set LineBreakage.
2) 设置断线。
3) Add Constraints.
3) 添加约束。
4) Change vertical content hugging priority.
4)更改垂直内容拥抱优先级。
5) On ViewDidLoad:
5) 在 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:
6) 在 TableView 自定义单元格上:
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
sizeToFit()
layoutIfNeeded()
}
回答by Vatsal Raval
Give your label constraint as top to Cell , Bottom to cell and keep your Leading and trailing constraint as it is. In
将您的标签约束设置为顶部到 Cell ,将底部设置为单元格,并保持您的前导和尾随约束不变。在
- (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
通过使用 UITableViewAutomaticDimension 将根据您标签的内容增加您的表格单元格高度,最重要的一点是,选择您的标签然后转到身份检查器并在行数中写入 0
回答by john raja
Swift 3 / Swift 4
斯威夫特 3 / 斯威夫特 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:
和 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
}
}
回答by zeeshan
Swift 4.2
斯威夫特 4.2
For the Basic
or Subtitle
type of cell, first in viewDidLoad
you do this:
对于Basic
orSubtitle
类型的单元格,首先viewDidLoad
要执行以下操作:
self.tableView.estimatedRowHeight = 44 // This is the default cell height
self.tableView.rowHeight = UITableView.automaticDimension
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.
然后选择标题并将其行数设置为 0。现在该行将根据标题文本调整其高度。你不需要做任何其他事情。
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.
您的自定义单元格类型也是如此。确保您在自定义单元格中使用的标签也设置为 0 行。