UITableView中的某些单元格重叠。

3
我有一个带有可变行高的表格视图。每个单元格的高度基于其中的文本量。该标签在IB中创建,具有尾部、领先和顶部约束,以便可以向下扩展。当我测试我的应用程序时,前几个单元格看起来不错,但一旦我滚动到底部,一切都开始混乱。单元格高度出现偏差,看起来像单元格重叠在一起。
-(TableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

postCell = [TableView dequeueReusableCellWithIdentifier:@"Cell"];

if (postCell == nil) {

    postCell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

 }


postCell.label.text = [array objectAtIndex:indexPath.row];

return postCell;


}

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


NSString *textString = [array objectAtIndex:indexPath.row];
CGRect frame = [textString boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 69, 1000.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0]} context:nil];
return ceil(frame.size.height) + 80;



}
1个回答

4
我认为您需要使用以下方法来计算单元格高度:
-(CGFloat)heightForText:(NSString *)text
{

    UITextView * textView = [[UITextView alloc] initWithFrame: CGRectMake(x, y, width, height)];
    textView.text = text;
    textView.font = [UIFont fontWithName:@"Helvetica" size:15];
    [textView sizeToFit];

    return textView.frame.size.height;
}

使用此方法计算单元格的高度后:
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
          CGFloat ht=[self heightForText:your text];
}

希望您能正确地将高度设置到表格视图单元格中。

这提供了与之前相同的结果。每个单元格都很好,除了最后两个或三个单元格。 - bpomp87
你需要对每个字符串使用这个方法,并获取所有字符串的高度。将这个高度设置为heightforrowatindexpath。 - Jashu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接