您的位置:首页 > 产品设计 > UI/UE

UIlabel自适应高度和UITableViewCell自适应高度

2015-08-10 22:37 375 查看
在做项目的时候发现从网上获取数据的时候在填充UILabel的时候需要UILabel自适应高度。这个问题其实很简单,只需要在storyboard里设置UILabel的高度,行数和lineBreakMode就可以了。但是因为TableViewCell的高度要根据Label的高度进行调节,所以这个我纠结了三天才终于做好。我的做法是这样的:

首先UILabel自适应高度:



首先如图设置lines为0,breakmode未word wrap,然后设置label的constraints中高度,因为我这里显示一行的高度是21,所以我在constraints中设置高度为21



然后设置constraint为height>=21



这样就做到了UIlabel的高度自适应。在接下来做UITableViewCell自适应的时候我们需要根据label的高度来调节cell的高度所以我们需要设置cell的高度,IOS有提供

CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)函数来确定每一个cell的高度。我开始只是返回了label得高度,但是因为label是作为cell的subview,但是cell并没有设置成为根据subview调整的模式,所以后来显示的就是cell永远是21的高度,而label的高度远远超过cell。开始我并不知道为什么后来调用了setNeedsLayout和layoutIfNeeded方法,问题得到了解决。
代码是这样的:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self heightForBasicCellAtIndexPath:indexPath];
}

- (CGFloat)heightForBasicCellAtIndexPath:(NSIndexPath *)indexPath {
static UITableViewCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"commentCell"];
});
//NSLog(@"1");
[self configureBasicCell:sizingCell atIndexPath:indexPath];
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
//CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
UILabel *label=[sizingCell viewWithTag:3];
// NSLog(@"label-height:%f",label.frame.size.height);
//NSLog(@"cell-height:%f",size.height);
return label.frame.size.height+label.frame.origin.y+5.0;
}

- (void)configureBasicCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = _comments[indexPath.row];
UILabel *label=[cell viewWithTag:1];
label.text=[dict objectForKey:@"username"];
label=[cell viewWithTag:2];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *created_time=[formatter dateFromString:[dict objectForKey:@"created_at"]];
[formatter setDateFormat:@"yyyy年MM月dd日"];
label.text=[formatter stringFromDate:created_time];
label=[cell viewWithTag:3];
NSString *ltext;
if(![[dict objectForKey:@"is_parent_comment"] boolValue]){
ltext=[NSString stringWithFormat:@"回复%@: %@",[dict objectForKey:@"parent_username"],[dict objectForKey:@"body"]];
}
else{
ltext=[NSString stringWithFormat:@"%@说: %@",[dict objectForKey:@"username"],[dict objectForKey:@"body"]];
}
label.text=ltext;
//NSLog(@"label height:%f",label.frame.size.height);
}
其中最重要的就是计算label的高度和下面这两句。
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: