I have a tableview with different cell heights using the heightForRowAtIndexPath:
method.
I would like to dynamically set the height of a UITable
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);
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;
}
You can set the frame of the tableView at any moment. You can even animate that change in size.
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)];
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()