bpomp87
bpomp87

Reputation: 81

UITableView some cells are overlapping

I have a tableview with varying row heights. The height of the cell is based on the amount of text in each cell. The label is created in IB with a trailing, leading, and top constraint so that it can expand downwards. When I test my app, the first cells are good, but once I scroll down everything starts to get messed up. The cell heights are 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;



}

Upvotes: 3

Views: 421

Answers (1)

Jashu
Jashu

Reputation: 1081

I think you have to use the below method for count the 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 use this method to count the height of the cell:

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

Hope you can correctly set height into tableview cell.

Upvotes: 4

Related Questions