Change Uitableview Height Dynamically

How to change cell height dynamically in UITableView static cell

If you are using autolayout. Add top, left and right constrain in to your label.

Then in heightForRowAtIndexPath create your cell

static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

Set values to label and calculate size of the label after setting the value

    [cell layoutIfNeeded];
return cell.label.frame.origin.y+cell.label.frame.size.height;

This will give you the exact hight of the label and your cell height will be same

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell.titleLabel.text=@"YOUR TEXT";
[cell layoutIfNeeded];
return cell.titleLabel.frame.origin.y+cell.titleLabel.frame.size.height;
}

Dynamic UITableView height

You need to set an IBOutlet to the NSLayoutConstraint that sets the tableView height (first you need create the height constraint with any value, doesn't matter) and then ctrl drag it to your class file

Sample Image

Then in your viewWillAppear you have to calculate the tableView height and set it. Like this:

var tableViewHeight:CGFloat = 0;
for (var i = tableView(self.tableView , numberOfRowsInSection: 0) - 1; i>0; i-=1 ){
tableViewHeight = height + tableView(self.tableView, heightForRowAtIndexPath: NSIndexPath(forRow: i, inSection: 0) )
}
tableViewHeightLayout.constant = tableViewHeight

And that's pretty much it. That will give your scrollView content size and shouldn't raise any warnings.

Dynamically change UITableViewCell height - Swift 4

You code crashes because of this line

let cell = tableView.cellForRow(at: indexPath) as! AvailableRideCell

From Apple Documentation we know that this method is used for optimization. The whole idea is to get cells heights without wasting time to create the cells itself. So this method called before initializing any cell, and tableView.cellForRow(at: indexPath) returns nil. Because there are no any cells yet. But you're making force unwrapping with as! AvailableRideCell and your code crashed.

So at first, you need to understand, why you should not use any cells inside the cellForRow(at ) method.
After that, you need to change the logic so you could compute content height without calling a cell.

For example, in my projects, I've used this solution

String implementation

extension String {
func height(for width: CGFloat, font: UIFont) -> CGFloat {
let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let actualSize = self.boundingRect(with: maxSize,
options: [.usesLineFragmentOrigin],
attributes: [NSAttributedStringKey.font: font],
context: nil)
return actualSize.height
}
}

UILabel implementation

extension String {
func height(for width: CGFloat, font: UIFont) -> CGFloat {
let labelFrame = CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)
let label = UILabel(frame: labelFrame)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height
}
}

With that, all you need to do is to compute your label and store its font.

var titles = ["dog", "cat", "cow"]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// number of rows is equal to the count of elements in array
return titles.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellTitle = titles[indexPath.row]
return cellTitle.height(forWidth: labelWidth, font: labelFont)
}

Dynamic rows height changing

If you'll need to update row height, all you need to do is to call this method when your content had been changed. indexPath is the index path of changed item.

tableView.reloadRows(at: [indexPath], with: .automatic)

Hope it helps you.

How to dynamically set tableView height?

Try following :

  1. Declare a variable inside your UIViewController subclass like this.
private var contentSizeObservation: NSKeyValueObservation?

  1. Inside viewDidLoad() or whenever your myTableView is set up, start observing contentSize changes.
contentSizeObservation = myTableView.observe(\.contentSize, options: .new, changeHandler: { [weak self] (tv, _) in
guard let self = self else { return }
self.myTableViewHeightConstraint.constant = tv.contentSize.height
})

  1. Do NOT Forget to clean this up in deinit call -
deinit {
contentSizeObservation?.invalidate()
}

This approach will make sure that your myTableView is always as big in height as it's content.

How to set Dynamically UITableView height in Swift?

Do like this,

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tblHeightConstraint.constant = downSelectionTbl.contentSize.height
}

How to dynamically set the height of a UITableView?

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


Related Topics



Leave a reply



Submit