【问题标题】:Increase height of tableview cell according to amount of UILabel text根据 UILabel 文本的数量增加 tableview 单元格的高度
【发布时间】:2016-04-11 08:57:31
【问题描述】:

我想通过使用自动布局根据文本量来更改我的表格视图单元格的高度。我尝试了以下代码,但它不起作用:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    AddTaskDetails *addTaskDetail = (self.tasksArray)[indexPath.row];
    CGFloat height;
    float textcount = [addTaskDetail.taskDetail length];
    if(textcount>60)
    {



            height = textcount-20;

        NSLog(@"%d,%f",indexPath.row,height);
    }
    else
    {
        height = 70;
    }
    return height;
}

【问题讨论】:

    标签: ios objective-c uitableview autolayout


    【解决方案1】:

    最好不要硬编码字符串所需的高度。而是使用属性文本高度属性。

    let attributes = [NSFontAttributeName : textFont,
            NSForegroundColorAttributeName : UIColor(
                red:25/255,
                green:176/255,
                blue:37/255,
                alpha:1.0)]
    
    
    let attrString:NSAttributedString? = NSAttributedString(string: yourString, attributes: attributes)
    let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(280.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
    return rect.height
    

    【讨论】:

      【解决方案2】:

      您需要在要呈现的字符串上使用 boundingRectWithSize:options:attributes:context

      这是一个常见问题,您可能会在搜索“具有动态高度的 UITableViewCell”时找到代码 sn-ps。

      【讨论】:

      • 您能否编辑我的代码并将其发布在您的答案中?
      • 这是一个常见问题,当您搜索“具有动态高度的 UITableViewCell”时,您可能会发现代码 sn-ps :)
      【解决方案3】:

      试试这个... 它会帮助你。

       NSString *classSubjecttxt =@"Some text";
       CGSize requiredSizeSubjetc =[classSubjecttxt sizeWithFont:[UIFont fontWithName:@"Trebuchet MS" size:12] constrainedToSize:CGSizeMake(labelwidth, CGFLOAT_MAX)];
      
      
      
              int height=YOUR DEFAULT HEIGHT;
      
               if(requiredSizeSubjetc.height >18){
      
                  height=height-18+ceil(requiredSizeSubjetc.height);
              }
      
              return height;
      

      【讨论】:

      • 我们可以计算出这个代码中的值,现在是 18:height=height-18+ceil(requiredSizeSubjetc.height);
      • 18 不是它的标签高度
      • 我正在使用您的代码。它在某些单元格中添加了一些空格,这不是我的要求。
      • 实际上它会在所有高度大于 18 的单元格中添加空格。如果标签大小大于 200,则会失败。
      • 您是否在代码中设置了正确的参数?请再次检查您的代码
      【解决方案4】:

      您不必以编程方式执行此操作。您可以使用界面生成器中的自动布局轻松完成此操作。

      • 只需给你的 UITableView 添加一个 UITableViewCell
      • 将其样式设置为自定义
      • 确保它在尺寸检查器中的尺寸是默认的
      • 向此单元格添加 UILabel
      • 设置其顶部、底部、左侧、右侧约束
      • 尺寸检查器将首选宽度设置为显式
      • 在属性检查器中将行数设置为“0”

      然后在 viewDidLoad() 中添加这些行

      tableView.estimatedRowHeight = 40.0
      tableView.rowHeight = UITableViewAutomaticDimension
      

      同时实现这些委托方法

      func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
          return UITableViewAutomaticDimension
      }
      
      func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
          return 44
      }
      

      【讨论】:

        【解决方案5】:
        - (CGFloat)getLabelHeight:(NSString*)textvalue
        {
            if (![textvalue isEqualToString:@""]) {
        
                NSString *string=textvalue;
        
                string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
                UIFont *font = [UIFont systemFontOfSize:12];
                CGSize constraint = CGSizeMake(SCREENWIDTH/1.0,NSIntegerMax);
                NSDictionary *attributes = @{NSFontAttributeName: font};
                CGRect rect = [string boundingRectWithSize:constraint
                                                   options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                attributes:attributes
                                                   context:nil];
        
                return rect.size.height;
            }
            else
            {
                return 20;
            }
        
        }
        

        然后你可以通过调用这个来获取大小:

        AddTaskDetails *addTaskDetail = (self.tasksArray)[indexPath.row];
            CGFloat textHeight = [self getLabelHeight:[addTaskDetail valueForKey:@"YOURKEY"]];
        

        您将在此处获取文本的文本大小,然后将其返回给heightForRowAtIndexPath

        【讨论】:

        【解决方案6】:

        首先您需要计算标签的高度。

        您可以通过调用以下函数来获取标签的动态高度:

        -(CGFloat)getDynamicHeightOfLabelWithFont:(UIFont *)font withText:(NSString *)text withFrame:(CGRect)initialFrame
        {
            UILabel *lblDummy = [[UILabel alloc] initWithFrame:initialFrame];
            lblDummy.font = font;
            lblDummy.lineBreakMode = NSLineBreakByWordWrapping;
            lblDummy.numberOfLines = 0;
            lblDummy.text = text;
        
            CGRect dummyFrame = initialFrame;
        
            dummyFrame.size = [lblDummy sizeThatFits:initialFrame.size];
            return dummyFrame.size.height;
        }
        

        您需要在heightForRowAtIndexPath 上调用此函数并返回高度。 并且您需要在cellForRowAtIndexPath 上设置框架并将框架设置为您的标签。

        【讨论】:

          【解决方案7】:

          1.创建一个自定义单元类。为 label/imageview 创建 outlet。

          2.在您的自定义单元类中添加此方法。

          -(void) layoutSubviews
          {
           [super layoutSubviews];
           [self.contentView layoutIfNeeded];
           self.yourLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.sentenceLabel.frame);
          }
          

          3.在您的视图控制器类中,创建自定义单元类的属性。

          -(DynamicTblVCell *)prototypeCell
           {
            if(!_prototypeCell)
             {
                _prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"DynamicTblVCell"];
             }
          return _prototypeCell;
           }
          

          4。在你的 viewDidLoad 添加这两行:

          self.tableView.estimatedRowHeight = 100.0;
          self.tableView.rowHeight = UITableViewAutomaticDimension;
          

          5。最后这样做:

          - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
            {
            static NSString *cellIdentifier = @"DynamicTblVCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
          
          //to configure a cell before it is displayed
           [self configureCell:cell forRowAtIndexPath:indexPath];
          
           return cell;
           }
          
          -(void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:  (NSIndexPath *)indexPath
           {
            if([cell isKindOfClass:[DynamicTblVCell class]])
             {
              DynamicTblVCell * textCell = (DynamicTblVCell *)cell;
              textCell.sentenceLabel.text = [NSString stringWithFormat:@"jhjshdjshdjhkjdhajsdhajsdh"];
              textCell.sentenceLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];  
             }
           }
          
          -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
           {
            [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];
            self.prototypeCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds));
            [self.prototypeCell layoutIfNeeded]; 
          
            CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
          
            return size.height+1;
          }
          
          
          -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
           {
             return UITableViewAutomaticDimension;
           }
          
          1. 将标签的行数设置为 0。
          2. 为顶部空间、底部空间、左右空间添加约束。不要为标签添加高度限制。

          【讨论】:

            【解决方案8】:

            使用下面的代码在有/没有自动布局的情况下获得更好的结果。需要计算标签的字体高度并根据您的要求设置位置。

            它也有助于计算collectionView的动态单元格高度。

            -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
            {
                CGSize constraint = CGSizeMake(screenWidth - 62, 20000.0f);
                CGSize size;
                NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
                CGSize boundingBox = [string boundingRectWithSize:constraint
                                                          options:NSStringDrawingUsesLineFragmentOrigin
                                                       attributes:@{NSFontAttributeName:self.titleLabel.font}
                                                          context:context].size;
                
                size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
                return size.height + 16;
            }
            

            【讨论】:

            • 我们可以使用自动布局来解决这个问题吗?因为我们在这个解决方案中硬编码了一些值。
            • @MuhammadUmair:如果您有硬编码值,那么为什么需要为单元格使用动态高度,只需为该字段设置适当的约束并使用它。如果您的文本是硬编码的,那么上面的代码也可以工作。希望我能正确理解。
            • 没有文本不是硬编码的,文本是动态的,这就是我需要这个的原因。
            • 是的,我已经尝试过了,但它在某些单元格中添加了一些空格。
            • @MuhammadUmair:您必须在“CGSize constraint = CGSizeMake(screenWidth - 62, 20000.0f);”中进行管理或'返回尺寸.高度 + 16;'线。然后你的问题就解决了。此代码仅供参考,不直接使用,您必须根据您的要求对其进行修改。希望您能投票回答,因为它对您有所帮助。
            猜你喜欢
            • 2017-04-26
            • 1970-01-01
            • 2023-03-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多