UITableViewCell布局里面文字的自適應

效果:

屏幕快照 2016-07-12 下午9.33.28.png
  • 1.需要在model里面再加一個高度的屬性

    @property(nonatomic,assign) float cellHeight;
    
  • 2.在model.m文件里兩種操作來控制cell里面文字的大小

    - (void)setText:(NSString *)text{
    
       _text = text;
    
     方法一:
       UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 5,      [UIScreen mainScreen].bounds.size.width-10, 0)];
       label.text = text;
       label.font = [UIFont systemFontOfSize:30];
    
       label.numberOfLines = 0;
    
      CGSize s = [label sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width-10, MAXFLOAT)];
      self.cellHeight = s.height + 310;
    
     方法二:
      CGSize size = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]} context:nil].size;
    
     self.cellHeight = size.height + 310;
      
     }
    
  • 3.自定義的label在重寫UITableViewCell里面進行返回model的高度

     -(void)setModel:(ModelCell *)model
    {
        _model = model;
    
        self.iconImage.image = [UIImage imageNamed:model.icon];
    
        self.Labeltext.font = [UIFont systemFontOfSize:30];
    
        CGRect rect = self.Labeltext.frame;
    
        rect.size.height = model.cellHeight-310;
        self.Labeltext.numberOfLines = 0;
    
        self.Labeltext.frame = rect;
    
        NSString *string = [NSString stringWithFormat:@"      %@",model.text];
    
        self.Labeltext.text = string ;
    
     }
    

需要強調的是:2里面和3里面字體的大小要保持一致,還有寬度

  • 4.在UITableViewController 里面cell高度返回里面寫入

      -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        ModelCell *model = dataArray[indexPath.row];
        return model.cellHeight;
    }
    
  • 5.具體的代碼如下github下載

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容