I am using a custom UITableViewCell which has some labels, buttons and image views to be displayed. There is one label in the cell whose text is a NSString object and the length of string could be variable. Due to this, I cannot set a constant height to the cell in the UITableView's heightForCellAtIndex method. The cell's height depends on the label's height which can be determined using the NSString's sizeWithFont method. I tried using it, but it looks like I'm going wrong somewhere. How can it be fixed?
下面是用于初始化单元格的代码。
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])
{
self.selectionStyle = UITableViewCellSelectionStyleNone;
UIImage *image = [UIImage imageNamed:@"dot.png"];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(45.0,10.0,10,10);
headingTxt = [[UILabel alloc] initWithFrame: CGRectMake(60.0,0.0,150.0,post_hdg_ht)];
[headingTxt setContentMode: UIViewContentModeCenter];
headingTxt.text = postData.user_f_name;
headingTxt.font = [UIFont boldSystemFontOfSize:13];
headingTxt.textAlignment = UITextAlignmentLeft;
headingTxt.textColor = [UIColor blackColor];
dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];
dateTxt.text = postData.created_dtm;
dateTxt.font = [UIFont italicSystemFontOfSize:11];
dateTxt.textAlignment = UITextAlignmentLeft;
dateTxt.textColor = [UIColor grayColor];
NSString * text1 = postData.post_body;
NSLog(@"text length = %d",[text1 length]);
CGRect bounds = [UIScreen mainScreen].bounds;
CGFloat tableViewWidth;
CGFloat width = 0;
tableViewWidth = bounds.size.width/2;
width = tableViewWidth - 40; //fudge factor
//CGSize textSize = {width, 20000.0f}; //width and height of text area
CGSize textSize = {245.0, 20000.0f}; //width and height of text area
CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]
constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat ht = MAX(size1.height, 28);
textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
textView.text = postData.post_body;
textView.font = [UIFont systemFontOfSize:11];
textView.textAlignment = UITextAlignmentLeft;
textView.textColor = [UIColor blackColor];
textView.lineBreakMode = UILineBreakModeWordWrap;
textView.numberOfLines = 3;
textView.autoresizesSubviews = YES;
[self.contentView addSubview:imageView];
[self.contentView addSubview:textView];
[self.contentView addSubview:webView];
[self.contentView addSubview:dateTxt];
[self.contentView addSubview:headingTxt];
[self.contentView sizeToFit];
[imageView release];
[textView release];
[webView release];
[dateTxt release];
[headingTxt release];
}
这个标签的高度和宽度都出了问题:
textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
在自定义UITableViewCell -controller中添加这个
-(void)layoutSubviews {
CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
self.frame = newCellViewFrame;
[super layoutSubviews];
}
在UITableView -controller中添加这个
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 1.5; // your dynamic height...
}
要有动态单元格高度作为标签的文本增加,你首先需要计算高度,文本将使用- highightforrowatindexpath委托方法,并返回其他标签的高度,图像(文本的最大高度+其他静态组件的高度),并在单元格创建中使用相同的高度。
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 2) { // the cell you want to be dynamic
NSString *text = dynamic text for your label;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
else {
return 44; // return normal cell height
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
}
label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];
[label setNumberOfLines:2];
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
label.adjustsFontSizeToFitWidth = NO;
[[cell contentView] addSubview:label];
NSString *text = dynamic text fro your label;
[label setText:text];
if (indexPath.row == 2) {// the cell which needs to be dynamic
[label setNumberOfLines:0];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
return cell;
}
我看到了很多解决方案,但都是错误的或不完整的。
你可以用5行viewDidLoad和自动布局解决所有问题。
这是针对目标C:
_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;
对于swift 2.0:
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
现在用xib创建单元格或在Storyboard中创建tableview
有了这个,你不需要实现更多或覆盖。(不要忘记数字os行0)和底部标签(约束)降级“内容拥抱优先级—垂直到250”
您可以在下一个url中下载代码:
https://github.com/jposes22/exampleTableCellCustomHeight
要设置行高和估计行高的自动尺寸,请确保以下步骤使,自动尺寸对单元格/行高布局有效。
分配和实现tableview dataSource和delegate
将UITableViewAutomaticDimension分配给rowHeight和estimatedRowHeight
实现委托/数据源方法(即hightforrowat并返回值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;
}
迅速:
@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
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
用于UITableviewCell中的标签实例
设置行数= 0(&断行模式=截尾)
针对它的superview/ cell容器设置所有约束(上、下、右、左)。
可选:如果您希望标签覆盖的垂直面积最小,即使没有数据,也可以设置标签的最小高度。
注意:如果你有多个动态长度的标签(UIElements),应该根据其内容大小进行调整:对于你想要以更高优先级展开/压缩的标签,调整“内容拥抱和抗压缩优先级”。
在这个例子中,我设置了低拥抱和高抗压缩优先级,这导致为第二个(黄色)标签的内容设置更多的优先级/重要性。