【问题标题】:cell height depending on a label text [duplicate]单元格高度取决于标签文本
【发布时间】:2014-07-17 21:53:54
【问题描述】:

我像这样从 CoreData 获取对象 self.name = [[abc anyObject] valueForKey:@"name"] 并显示它:

cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.name];
cell.nameLabel.numberOfLines = 0;
cell.nameLabel.lineBreakMode = NSLineBreakByWordWrapping;

如何为我的单元格获得正确的高度以将其返回 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

【问题讨论】:

    标签: ios uitableview


    【解决方案1】:

    只需在 UITableViewCell 类中实现一个静态方法,该方法能够根据提供的字符串和宽度计算单元格高度。单元格应该知道它是如何构造的以及它将占用多少空间。

    例如:

    + (CGFloat)heightForWidth:(CGFloat)width text:(NSString *)text {
    
        CGFloat height = ... ;
    
        return height;
    }
    

    【讨论】:

    • 我不明白。我有自己的单元格类,以及如何获得'CGFloat height ='?
    • 你不小心把整个有趣的部分都搞定了。
    • 如果您的单元格仅包含一个多行标签,则此方法看起来像这样(只需使用与标签相同的标签字体和换行模式:+ (CGFloat)cellHeightForTitle:(NSString *)title width:(CGFloat)width { CGFloat height = 0.0; height += 2 * verticalMargin; height += [title sizeWithFont:font constrainedToSize:CGSizeMake(width - 2*sideMargin, MAXFLOAT) lineBreakMode:lineBreakMode].height; return height; }
    【解决方案2】:

    尝试在情节提要中禁用自动布局,然后调用 sizeToFit。

    cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.name];
    cell.nameLabel.numberOfLines = 0;
    cell.nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [cell.nameLabel sizeToFit];
    

    【讨论】:

      【解决方案3】:

      这是解决方案:

      - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
      {
          CGSize constraintSize = CGSizeMake(286.0f, CGFLOAT_MAX);
          UIFont *theFont  = [UIFont systemFontOfSize:14.0f];
          CGSize theSize;
      
          if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
          {
              CGRect frame = [[self.mArray objectAtIndex:indexPath.row] boundingRectWithSize:constraintSize options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:theFont} context:nil];
          theSize = frame.size;
          }
          else
          {
              theSize = [[self.mArray objectAtIndex:indexPath.row] sizeWithFont:theFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
          }
      
          return theSize.height;
          }
      

      - (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath我也用过cell.label.numberOfLines = 0

      如果您在一行中使用多个标签 - 在 CGSizeMake(286.0f, CGFLOAT_MAX) 中使用低于 286.0f 的值(例如 150.0f)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-06
        • 2013-07-25
        • 2019-09-12
        • 2017-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多