【问题标题】:iPhone: How to increase the height of cell dynamically as per the stringiPhone:如何根据字符串动态增加单元格的高度
【发布时间】:2011-12-29 09:05:47
【问题描述】:

我在我的应用程序中使用带有标题的 UITableView,我想在 tableview 的单元格中添加字符串。在标题下方的单元格中,我要填充字符串数据,并根据字符串的大小增加单元格的高度

为了更好地理解,我附上了文件。

我已经检查了link1link2link3

但我无法得到我想要的答案。

为了更好地理解,我也附上了图片。

标签说明指示我的标题,并在下一个单元格中添加字符串。

那么如何根据字符串长度增加单元格的高度。

提前感谢。

【问题讨论】:

    标签: iphone objective-c uitableview


    【解决方案1】:

    实现方法

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
       //return appropriate value based on IndexPath.row
    
      UIFont *font = textLabel.font; // use custom label's font
      NSString *myText = @"your text for row at index path";
      CGSize size = [myText sizeWithFont:font forWidth:textLabel.frame.size.width lineBreakMode:UILineBreakModeWordWrap];
      return (size.height+20); //10 pixels space above the textlabel and below 10 pixels space
    }
    

    如您所引用的链接中所述。

    【讨论】:

    • 我正在使用cell.textLabel.text 分配单元格值。我还需要什么吗?
    • cellForRowAtIndexPath 中,您通过cell.textLabel.text 按原样分配文本。无需更改。我已经编辑了我的答案。 PL。见
    • UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 我在这一行收到错误消息 EXC BAD ACCESS。
    【解决方案2】:

    使用以下委托方法:

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
       //return appropriate value based on IndexPath.row
    }
    

    在此方法中,从数据源数组中,检查特定行的字符串长度并相应地返回高度。

    【讨论】:

      【解决方案3】:

      试试这个代码来确定单元格大小。

      - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
      {
      
      
          NSString *text =@"your String";
      
          CGSize constraint = CGSizeMake(CellContentWidth - (CellMargin * 2), 20000.0f);
      
          CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
      
          CGFloat height = MAX(size.height, 44.0f);
      
      
          return height + (cellMargin* 2);
      
      }
      

      此代码用于单元格标签高度。

          NSString *text = [arr objectAtIndex:indexPath.row];
      
          CGSize constraint = CGSizeMake(labelwidth , 20000.0f);
      
          CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
      
          CGFloat height = MAX(size.height, 44.0f);
      
          cell.lbl3.frame=CGRectMake(X,Y ,W, height);
      

      【讨论】:

        猜你喜欢
        • 2017-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多