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

来源:互联网 发布:网络综艺节目的发展 编辑:程序博客网 时间:2024/05/17 23:16
























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


0 0
原创粉丝点击