iOS UITableViewCell自適應高度

  在cell.m文件中spa

  1)初始化方法中:blog

 

 self.lalName=[[UILabel alloc] initWithFrame:CGRectMake(71, 5, 250, 40)];
    [self addSubview:self.lalName];

 

 2)建立方法:ip

 

//給用戶介紹賦值而且實現自動換行
-(void)setIntroductionText:(NSString*)text{
    //得到當前cell的高度
    CGRect frame=[self frame];
    //文本賦值
    self.lalName.text=text;
    CGSize size=CGSizeMake(300, 1000);
    //設置label的最大行數
    self.lalName.numberOfLines=10;
    CGSize labelSize=[self.lalName.text sizeWithFont:self.lalName.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping];
    self.lalName.frame=CGRectMake(self.lalName.frame.origin.x, self.lalName.frame.origin.y, labelSize.width, labelSize.height) ;
    
    //計算出自適應的高度
    frame.size.height=labelSize.height+20;
    self.frame =frame;
    
}

  

  在ViewController中:it

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *acell=@"acell";
    TextKitTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:acell];
    if (!cell) {
        cell=[[[NSBundle mainBundle] loadNibNamed:@"TextKitTableViewCell" owner:self options:nil]lastObject];
    }
    
 
    [cell setIntroductionText:@"where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you?where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you? where are you?"];
    return cell;
    
}

  固然別忘記了返回給cell高度io

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[self tableView:self.tableViewTextKit cellForRowAtIndexPath:indexPath];
    NSLog(@"height===%f",cell.frame.size.height);
    return cell.frame.size.height;
}
相關文章
相關標籤/搜索