Automatically adjusting UITableView height to display only the UITableViewCell(s) present - ios

It seems that UITableView does not auto-calculate the exact height needed to cover all the visible cells, instead, it substitutes any extra area with empty rows.
I'd like to calculate the exact height needed to cover only the visible cells, as to rid my UITableView of those ugly empty rows. I am quite aware that this can be done manually using the Interface Builder, however there must be a more efficient and dynamic approach to this problem.

You can use the table view's content size to determine how much space the table wants.
CGFloat height = myTableView.contentSize.height;
This height will automatically consider headers, footers, and the size and number of cells, and pretty much anything else. And it's all dynamic, so if you decide to go to a 7 row table in the future, it will still work without a problem and without needing to change that piece of code. The only time you would need to change it is if you decided at some point that you no longer want to show the whole table anymore.
And a quick tip - you'll probably want to also set [myTableView setScrollEnabled:NO]. Disabling scrolling will prevent the table from "bouncing" if the user does try to scroll it - I just think that bouncing looks really silly if all the content of the table is being shown at once.
You can then use this height to either
adjust the constraints on your table view (if you are using Autolayout)
adjust the frame of your table view (if you use the old springs-and-struts approach)

Use the following code to get set cellHeight member variable and use it where ever required.
_cellHeight = floorf((CGRectGetHeight(self.tableView.bounds))/5);
This should give you height of each row and it will handle all cases.
The above code has to be used in following methods.
-(void)viewWillLayoutSubviews;
- (void)viewWillAppear:(BOOL)animated;
I hope this helps.

Related

Have autolayout CHANGE the height of a cell, already on screen, in a dynamic height cell table?

Nowadays fortunately it's trivial to have an iOS table where every cell has a dynamic height. So in the cell vertical constraints ..
---- top of content view
- vertical constraint to
-- UILabel, with, .lines set to zero
- vertical constraint to
---- bottom of content view
Assume the UILabel texts vary greatly one word, 20 words, 100 words,
In the table set
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 200 // say
and you're done, these days it works perfectly of course.
However, I had the common situation where you load the table, imagine ten cells.
I populate the UILabel with "Loading..."
Only then - say, a second or two later - do we get the information for the text content. It arrives say a second later and the cell changes the text to "Some long text .. with many lines".
In fact I was surprised to learn it seems UITableView does NOT handle this. The cell in question gets stuck on the original short height.
So, after the larger text is set, I tried all permutations of the usual:
maintext.sizeToFit()
contentView.layoutSubviews()
contentView.layoutIfNeeded()
on the cell, doesn't work.
I tried sending a setNeedsLayout and/or layoutIfNeeded to the table itself, doesn't work.
I thought about .reloadData() on the table itself but - doh - that would again trigger the content being drawn from the server and loaded again, so that's not ideal.
Please note that:
Obviously there are any number of workarounds for the specific example such as not using dynamic data
I am completely aware how to manually animate the height of one cell (like when you "expand" one to show something else when the user taps)
This question is about autolayout and table view - which, thanks Apple, nowadays flawlessly handles completely dynamic cell heights involving UILabels with lines zero.
But what about if the text in such a label changes?
It seems that the table view system does NOT handle this.
Surely there's a way?
When the content of a cell changes the layout (in this case, the height) you must inform the table view that the layout has changed.
This is commonly done with either:
tableView.beginUpdates()
tableView.endUpdates()
or:
tableView.performBatchUpdates(_:completion:)
Why is that not triggered automatically?
I suppose it could be to allow you to do your own animation, or you may want to delay the update, or some other reason that doesn't come to mind at the moment.
Or, it may be due to maintaining backward compatibility?
I don't know. I imagine Apple could tell us...

hide/ show controls in View controllers

My application gathers input from users and hence it is full of Labels, text boxes and buttons and I have to show or hide set of labels and text boxes based on certain conditions.
To accomplish it, I did the following.
Set fixed height (lets say 30) for all the controls
Set height constraint on each of the controls and created an outlet to the height constraint in the ViewController
Alter the heightConstraint.constant value programatically (between 0.0 and 30.0) based on the scenarios.
Having programmed like this, it is very difficult for me if there is any change in layout. (i.e., if user requested to add/remove any particular control from the view Controller).
I am using Auto Layout constraints. Could anyone suggest if there is a better way to accomplish my goal.
I am using IOS9 and Swift.
Many thanks in advance.
You can use UITableViewController with static cells for this case.
For hide/show row or section, you can change the size in the tableView:heightForRowAtIndexPath method.
UITableViewController automatically manages the layout and with static cell you can even create outlet for all the controls.
Have you considered using a table for this? It has mechanisms for inserting and deleting rows and would manage the layouting for you - only part you'd need to care about are the contents of the cells.
Instead of making IBOutlets to the height constraints of all the views that you might need to hide, you can just use the hidden property of UIViews to hide/show the view.
In case you need the view to make space for other views, you could set a simple animation and move the view out of screen bounds. You might face issues with layout constraints but it's surely worth the effort from a UI/UX perspective.
Additionally, if you know that you don't need a view any more you can even remove the view from it's superview.

Resizing UITableViewCell to fit Content Performance

I am trying to create a table to show posts by users with possibly variable lengths. I want each cell in my table to resize to fit the content of the UILabel containing the text of the post. Currently I am doing this with auto-layout, programmatically setting constraints and calculating the height of the table view cell based on the height of the UILabel. Everything looks as I want it to, except when rapidly scrolling through the table the performance is horrendous, with the CPU getting fully maxed out and unable to keep up with setting the constraints for each cell as they are reused and placed with new text.
I was wondering if anyone knows of a better way to do this. Is there a way I can continue to use auto layout to size my cells without sacrificing performance? Or would the best solution be to create different sized cells with different identifiers, and just choose the best fit based on the UILabel text size.
I also read somewhere that UICollectionView has much better performance in displaying variable-sized content, would it be worthwhile/possible to try configuring a UICollectionView to display the messages, and somehow make it look like a UITableView?
Essentially I just need a suggestion on how to display messages of variable sizes (up to about 7 or 8 lines of text max) in a TableView-like manner without causing massive slowdowns as the user rapidly scrolls through the table.
Thank you
The best trick in the book for things like this is cacheing. Add to your model anything that's expensive to compute (not the views themselves, but the computational results, like view bounds sizes). Make your datasource methods all about looking up and assigning, not at all about computing.
The way I had implemented adding the constraints, the constraints were updated whenever [self updateViewConstraints] was called, regardless of whether or not the cell had already had its constraints calculated and applied. I resolved this by adding a BOOL property to my custom TableViewCell called didUpdateConstraints, and setting it to YES as soon as constraints are updated the first time. Then in my [self updateViewConstraints] method I only update the constraints if !self.didUpdateConstraints
Now that constraints are not being needlessly updated when all views have already been correctly constrained, the performance is significantly better, and I don't observe any slowdown upon scrolling through the table.

Must I use -[UITableViewCell contentView] for uneditable cells?

I'm building something similar to the compose page of the native iPhone Mail app.
But, I'm putting two text fields on one row, and I want to separate them with a vertical divider (an additional view) that's the same color & weight as the horizontal cell separators.
Apple's docs say:
If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.
But, what if I know, like in this case, that my cell will never go into editing mode?
Also, the horizontal cell separators are subviews of the cell, not the cell's content view. So, I think it'd also make sense if I added the vertical divider to the cell, not the cell's content view.
Can I just add additional views to the cell itself, instead of its content view?
You can add additional views directly to the cell, but it's best practice to add them to the cell's content view. Even if you're cells never go into editing mode, this is what Apple and other developers that may be working on your code (or you in the future) are expecting. So, this will make it easier for them to work with your app.
For example, what if Apple hypothetically decided to put gutters on the left & right side of plain style table views in a future release of iOS? Then, they would probably inset the cell's content view but not the cell itself. That way, if you position your additional views relative to the content view, your app has a better chance of looking good and the additional views have a better chance of not getting clipped by Apple's hypothetical gutters. OK, I doubt Apple would do such a thing, but the point is that if you add your additional views to the cell's content view instead of the cell itself, you're code will be more robust.
For your specific case, I still recommend adding the vertical divider to the cell's content view because you can. You might even consider setting the tableView.separatorStyle = UITableViewCellSeparatorStyleNone and redrawing custom separators by adding a separator view to the bottom of each of your cells' content views. This way, you can be sure that the style of the vertical divider you add will always match that of the separators. Again, this will make your code more robust and protect you if Apple decides to change the style of their separators. Sure, you can use cell.separatorColor. And, you can guess the separator weight with cell.frame.size.height - cell.contentView.frame.size.height. But, such cleverness might get you in trouble.
As the Buddha admonishes Siddhartha, "Beware of too much cleverness!"

IOS Complex view

(please forgive my english)
I'm new at IOS developing but I've a good skill on other programming languages (mainly c#).
I'm trying to develop a test app with a main window.
Inside that window there is a scrollview with fixed size. inside that scrollviewer there is a view containing some stacked couples of one TextField and one Label: I can't know - ad design time - how many "rows" of them I have to put into.
My problems is:
I can put on the view the first couple (a textfield and, next, a label). Label size can be one or several rows high ,so I've to set multiline and sizeToFit
How can I put the second couple (and so on) without overlap the existing labels..? I can't use a table because between rows there are other labels (title of section).
Do I have to calculate the height of each label and programmatically calculate where to draw the next? Is there a more efficient way?
I don't need code, please just some hints or some keyword to googling on.
Many thanks.
I don't see why you can't use a UITableView, you can set up cells with all the controls you need in it. Either way, using a UITableview won't make the job any easier (just more memory efficient if you have many rows).
The only way that I see is, as you said, to calculate where the next 'row' should be placed (depending on the height of your previous rows). You'll also need to calculate the entire height, in order to set it to the contentSize of the UIScrollView.
Instead of UILabel you can also use a non editable UITextView, since it'll be easier to get its size (after you set the text, you can set the size of a UITextView to be equal to its contentSize)

Resources