EXC_BAD_ACCESS in heightForRowAtIndexPath iOS

后端 未结 5 1378
眼角桃花
眼角桃花 2020-11-28 14:27

I\'m working on an application where I have a custom subclass of UITableViewCell. I want to make the cell\'s height dynamic based on the text inside it. I try do do that in

5条回答
  •  半阙折子戏
    2020-11-28 15:03

    In this case you should call UITableViewDataSource method for getting cell for indexPath instead of cellForRowAtIndexPath: method of UITableView because at the moment when tableView: heightForRowAtIndexPath: first time called there are no any cells in tableView.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
        PostCell *cell = (PostCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
        CGSize postTextSize;
        if (![cell.postText.text isEqualToString:@""]) {
        postTextSize = [cell.postText.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(cell.postText.frame.size.width, 200)];
        } else {
            postTextSize = CGSizeMake(cell.postText.frame.size.width, 40);
        }
    
        return postTextSize.height + cell.userName.frame.size.height + 10;
    }
    

    It works and no causes EXC_BAD_ACCESS exception.

提交回复
热议问题