我必须解决现有项目中的一些问题(Objective,Xcode 7.3,iOS)。
这里我有一个表视图,在这个视图中我需要一些可调整大小的单元格来适应内容。这些细胞包括标签。该项目使用UITableViewAutomaticDimension,但它似乎不能正常工作。单元格中的文本超出了右边框。
所以现在我检查了几点:
heightForRowAtIndexPath方法只包含return UITableViewAutomaticDimension;。下面是使用UITableViewAutomaticDimension的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.estimatedRowHeight = 50.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
} Constraints screenshot <======
发布于 2016-06-20 09:55:43
尝尝这个
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 186, 0)]; //max width that is allowed for label
lbl.numberOfLines = 0;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
int GAP = 3;
float height = 0;
float fontSize = 14;
NSString *cellText = yourtext;
lbl.font= [ UIFont fontWithName:FONT_NAME_Ubuntu size: fontSize];
bl.text = cellText;
[lbl sizeToFit];
height += lbl.frame.size.height;
height += GAP;
return height;
} 或者试一试
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
/*
for dynamic cell heigh according to the description display in cell
*/
NSDictionary *dict1 = (NSDictionary*)[array objectAtIndex:indexPath.row];
NSString *cellText = [dict1 valueForKey:@"test"];
UIFont *cellFont = [UIFont fontWithName:FONT_NAME_GOTHAM_4 size:11.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 80;
}发布于 2016-06-20 09:57:08
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}发布于 2016-06-20 10:11:46
您需要在IB或代码中设置
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis: UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis: UILayoutConstraintAxisVertical];在设置文本之后,调用这个
[cell setNeedsDisplay];
[cell layoutIfNeeded];希望能帮上忙。我是从苹果的“自我标尺”中学到的。
https://stackoverflow.com/questions/37919384
复制相似问题