Resizing UITableViewCell to fit Content Performance - ios

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.

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...

Best approach to showing or hiding dynamic content in iOS

I've been doing iOS for a while now, but when it comes to dynamically hiding / showing elements, I'm a bit lost.
Coming from Android, I'm used to being able to simply set views to visibility gone, but this doesn't exist on iOS.
So let's say I have the following scenario:
Basically I want to have a table, but the table should not fill the entire view controller. Instead it should leave place for optionally either a button, a multiline label, or possibly both at the bottom (if visible, these should be fixed, not scroll).
One way to solve this would be to use auto layout and modify constraints, like adding a zero height constraint. But that would make iOS kill one of the other constraints, which would make it hard to change it again. For the label, I wouldn't always want to have a height constraint, because it could be multiline, and should take the size it needs.
Maybe it's easier to skip autolayout here and modify frames instead, I don't know.
My question is: What approach would be best here?
Is there some other way of doing this I haven't thought of, or do I have to try to do what I described above?
I'm not primarily looking for code (code can be ok), but I'm more interested in a description of how it can be done.
I'd like to support iOS 7.
This problem had a variety of solutions, and opinion based, but I'm facing such questions a lot, when I don't know what to choose and what would be the "right thing".
So, I my opinion, the best solution here is using autolayout, you need to set height of label manually, but you have a few methods for this, at least you can play with it and if you don't succeed ask question about it. Using frames, you'll face same problem of calculating height, right? But with auto layout, you only need to set height, vertical space to 0, when you need to hide message.
You can also use constrains with priority lower 1000, and remove completely constraints from message (button, label) if you don't need it at all anymore.
For example, taking your layout image, you can make UIView with subviews: button, label. Top constraint connect to the UITableView, other constraints to the sides.Label and button will calculate the view's height. The only question here is label height.
So in ios assuming that the background of both these objects is opaque only the front most view in the Heirarchy will be visible and interactable, An easy solution would be to change the different frames of these two things you need and make sure they are in the back of your view heirachy, and when you need them to appear use view.bringSubviewToFront(mySubview) and view.pushSubviewToBack(mySubview) to make it disappear again. View obviously would be referring to main view of your view controller.

Is subclassing UIView the right way to go about an unknown number of these custom objects?

I have a screen in my app that pulls an unknown sized array from my user object, and must display an object for each item in the array that consists of a UIImageView for my background image, a UISwitch to activate/deactivate that particular item, a label with the name of the item, and a label that corresponds to the name of the item.
These are displayed in a UIScrollView, since there are nearly always going to be more items than will fit on the screen, especially on the iPhone 4.
I had initially quickly thrown together a static screen that consisted of 20 of these objects, but have found that I will often be exceeding that number of items in the array, and need to convert to a dynamic solution.
I have not used subclassing at all yet, and want to be sure that this is the proper solution before I dive into the implementation. Adding one subclass to my scrollView sounds a lot cleaner than adding each of those components individually and figuring out the spacing for various screens.
If this is the proper solution, are there any resources you could point me to to learn about how to properly do this subclassing? I.e., how to add a constructor for the objects where I can add the contents of the labels and state of the switch, and programmatically add constraints. I've only used constraints from the storyboard.
If you do not think that subclassing UIView would be the proper way to do this, what other solution would you suggest? I'm admittedly a novice when it comes to iOS development, so I apologize that this post seeks advice on where to start rather than help fixing a specific part of an implementation.
You should use UITableView or UICollectionView for that, and subclass UITableViewCell or UICollectionViewCell to create your custom view hierarchy.
UITableView and UICollectionView will handle reusing of cells which will help in memory management.
Update:
as you want to use UITableView so to add spacing between cells set number of sections to number of elements and then add header for section and set its height you can do that by implementing UITableViewDelegates visit below links for detail about UITableView and UITableViewDelegates
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/

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

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.

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