UITableViewCell布局里面文字的自適應(yīng)

效果:

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

    @property(nonatomic,assign) float cellHeight;
    
  • 2.在model.m文件里兩種操作來(lái)控制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在重寫(xiě)UITableViewCell里面進(jìn)行返回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 ;
    
     }
    

需要強(qiáng)調(diào)的是:2里面和3里面字體的大小要保持一致,還有寬度

  • 4.在UITableViewController 里面cell高度返回里面寫(xiě)入

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容