UITableView some cells overlap

I have a table with different row heights. The height of a cell depends on the amount of text in each cell. The label is created in IB with an end, leading, and top constraint so that it can expand downward. When I test my application the first cells are fine, but as soon as I scroll down, things start to get messed up. Cell height is off and it looks like the cells are overlapping.

-(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;



}

      

+3


source to share


1 answer


I think you need to use below method to calculate cell height:

-(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;
}

      

After using this method to calculate the height of a cell:



- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
          CGFloat ht=[self heightForText:your text];
}

      

Hope you can set the height in the table cell correctly.

+4


source







All Articles