您的位置:首页 > 移动开发 > IOS开发

ios学习笔记: TableView利用label调整cell高度

2015-06-06 14:52 549 查看


tableView中:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath {
    //模拟数据
    MC_EatCommentModel* model = [self.commentItemsobjectAtIndex:indexPath.row];
   //根据labei设置高度
    CGSize size =CGSizeMake(260,1000);
    CGSize labelSize = [model.commentsizeWithFont:[UIFontsystemFontOfSize:12.0]constrainedToSize:sizelineBreakMode:NSLineBreakByWordWrapping];
    return labelSize.height +44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
    staticNSString *CellIdentifier =@"MC_EatCommentCell";
    BOOL nibsRegistered =NO;
    if (!nibsRegistered) {
        UINib *nib = [UINibnibWithNibName:NSStringFromClass([MC_EatCommentCellclass])bundle:nil];
        [tableView registerNib:nibforCellReuseIdentifier:CellIdentifier];
        nibsRegistered = YES;
    }
    MC_EatCommentCell *cell = (MC_EatCommentCell *)[tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
    self.commentModel = [self.commentItemsobjectAtIndex:indexPath.row];
    
    cell.userName.text=self.commentModel.userName;
    cell.label_time.text=self.commentModel.time;
    //自适应高度,传入cell中
    [cell setCommentText:self.commentModel.comment];
    cell.m_userModel =self.commentModel;
    [cell.iconsetBackgroundImage:[UIImageimageNamed:self.commentModel.icon]forState:UIControlStateNormal];
    return cell;
}
cell中:

-(void)setCommentText:(NSString*)text{
    self.comment.text = text;
    //设置label的最大行数,这里设为0,而用 size.height去限制高度。eg当设置为3时 label会自动调节高度,不再紧贴着label上方
    self.comment.numberOfLines =0;
    CGSize size =CGSizeMake(260,1000);
    CGSize labelSize = [self.comment.textsizeWithFont:self.comment.fontconstrainedToSize:sizelineBreakMode:NSLineBreakByWordWrapping];
    self.comment.frame =CGRectMake(self.comment.frame.origin.x,self.comment.frame.origin.y,
labelSize.width, labelSize.height);
    self.comment.textAlignment =NSTextAlignmentLeft;

}
参考:http://blog.csdn.net/swingpyzf/article/details/18093959
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息