user2588945
user2588945

Reputation: 1681

How to dynamically set the height of a UITableView?

I have a tableview with different cell heights using the heightForRowAtIndexPath: method.

I would like to dynamically set the height of a UITableView. At the moment I'm setting the dimensions of the tableView in viewDidLoad method using:

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, 400)];
self.tableView.dataSource = self;
self.tableView.delegate = self;

I thought maybe I could add this: self.tableView.contentSize.height; but the problem of course is that the content size is only calculated after the table loads, so if I put it in

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, self.tableView.contentSize.height)];

it doesn't work.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *description = [photosFromCommentsArray objectAtIndex:indexPath.row];
    //   NSLog(@"description is %@",description);

    if(description == (id)[NSNull null])
    {
        return 70; 
    }
    else
    {
        return 200;
    }
}

Upvotes: 7

Views: 11064

Answers (5)

Tej Patel
Tej Patel

Reputation: 119

Step 1 : add observer in viewDidLoad()

self.tableView.addObserver(self, forKeyPath: "contentSize", options: [], context: nil)

Step 2 : add method

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    self.tableViewHeight.constant = tableView.contentSize.height
}

Step 3 : Remove Observer

override func viewDidDisappear(_ animated: Bool) {
    self.removeObserver(self, forKeyPath: "contentSize", context: nil)

}

Alternate Solution :

    tableView.separatorStyle = .none
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = CGFloat(70.0)

self.tableViewHeight.constant = CGFloat.greatestFiniteMagnitude self.tableView.layoutIfNeeded()

self.tableView.reloadData()

override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews()

    UIView.animate(withDuration: 0, animations: {
        self.tableView.layoutIfNeeded()
    }) { (complete) in
        var heightOfTableView: CGFloat = 0.0
        // Get visible cells and sum up their heights
        let cells = self.tableView.visibleCells
        for cell in cells {
            heightOfTableView += cell.frame.height
        }
        // Edit heightOfTableViewConstraint's constant to update height of table view
        self.tableViewHeight.constant = heightOfTableView
    }
}

Another Solution :

self.tableViewHeight.constant = CGFloat(arrVideoList.count * 80)
self.view.updateConstraintsIfNeeded()

Upvotes: 1

Mihir Oza
Mihir Oza

Reputation: 2796

Try this in viewDidLoad:

[tableView setFrame:CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y + 4, tableView.frame.size.width, tableView.frame.size.height - 65)];

Upvotes: 0

wattson12
wattson12

Reputation: 11174

Add an observer for the contentSize property on the table view, and adjust the frame accordingly

[self.tableView addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];

then in the callback:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    CGRect frame = self.tableView.frame;
    frame.size = self.tableView.contentSize;
    self.tableView.frame = frame;
}

Upvotes: 20

Nirmalsinh Rathod
Nirmalsinh Rathod

Reputation: 5186

Hello You can get height of text with below code and set height according to it.

CGFloat textViewWidth = CGRectGetWidth(textView.bounds);
CGSize inset = CGSizeMake(5.0,5.0);
CGSize stringSize = [myString sizeWithFont:textView.font constrainedToSize:CGSizeMake(textViewWidth-2*inset.width,1024) lineBreakMode:UILineBreakModeWordWrap];
BOOL textOutOfFit = stringSize.height+2*inset.height>CGRectGetHeight(textView.bounds);

Upvotes: 0

Joride
Joride

Reputation: 3763

You can set the frame of the tableView at any moment. You can even animate that change in size.

Upvotes: 0

Related Questions