Test dequeueReusableCellWithIdentifier:forIndexPath - ios

I read a lot about reusing table cells in different questions here.
I implemented a subclass of UITableview (in Swift)
Registered this class in ViewDidLoad() of my ViewController (I'm not using storyboard)
and use dequeueReusableCellWithIdentifier:forIndexpath in tableView's
cellForRowAtIndexPath
As far as i know this should reuse the cells.
However is there a way to test if the cells are actually reused?
For example in Instruments or by printing in the debugger.
Thank you for your help!

There is a number of ways to do it.
First of all, you can just write something to log in the initWithStyle:reuseIdentifier:. You'll see as much log entries as there are cells on the screen at the same time.
Second: you can mark your cells somehow in cellForRowAtIndexPath. For instance, cells have tags which are set to 0 by default. So when you get a cell from dequeueReusableCell..., if it has a tag, which is equal to 0, you set it to something else. Otherwise, you've just received a reused cell. You can also set the tag of the first cell to 1, then 2 for the second cell, etc. This way you'll also find out the number of cells that you use. You just need to keep track of the largest tag so far.
You can also add some custom property and use it the same way as the tag.
Another option is to print cells in the debugger. as #RichTolley suggested in a comment above. But to my mind it is not very convenient (manually comparing pointers to every cell).

The eayest way is to set a tag in cell for cell.tag = indexPath.row+1 (add one prevent from set default 0 value) and set breakpoint condition as on the picture. If tag will be different than 0 breakpoint stops and print tag on console. How to set condition breakepoint

Related

How to correctly implement dynamic prototype cells in a UITableView

I, previously, had an issue where my UITextView was incapable of functioning, entirely. Since then, another user has taken a lot of time to help me solve this issue. I can say that it was successfully resolved. However, I now have an additional issue. When attempting to utilize properties of a prototype cell, which I’ve already made a UITextViewCell custom class for, as well as linked all the appropriate items, I run into an issue where the properties of the cell are being ignored. Only one property every shows, the dimensions are incorrect and the property that shows doesn’t have correct formatting. If you have time, can someone do a step by step, possibly with images, detailing EXACTLY what to do to make a custom table view cell that initializes correctly? You can assume that the table view and accompanying arrays etc. are already correctly initialized. Thank you.
Make sure you set both values...
With the Table View selected - note the Value for Row Height:
With the Cell selected - note the Value for Row Height:

Name Label overlapping each time it is loaded

Our app has a social feed with a name label similar to Facebook with a FeedController and FeedCell class. Each time we scroll back to a previously loaded cell, it reloads, so the name label becomes darker, the text becomes bolder and starts to overlap. How do we fix this? We tried the prepareToReuse method and setting the cell's label to nil, but that did not help. Any help would be greatly appreciated!
It appears that you're regenerating the label and adding it to your cell's content view every time that the label is reused.
Inside your FeedCell class, make sure to only initiate your interface elements in your initializer. From there, you can fill your cell with data in the cellForRowAtIndexPath: method of your UITableViewDataSource.
Inside cellForRowAtIndexPath:, make sure to not add any views to the cell as this could contribute to the issue you're describing. As a rule of thumb, I make sure to initialize the views in the cell subclass's initializer, and only manipulate properties of these views (like hidden, alpha, etc) when working with the cells.
Moving forward, you can use prepareForReuse to clear any data from your cell that may be leftover from the previous time the cell was used. In many cases though, this isn't necessary as the data will be changed in cellForRowAtIndexPath:.

configure UICollectionView cell on initial lookup

I am getting cells for a UICollectionView by calling dequeueReusableCellWithReuseIdentifier:. I want to set some specific configuration information the first time my cell is returned from this method and not subsequently when it gets reused. Is there a hook somewhere where I can run "one time" code on collection view cells?
Obviously I could just set this information every time or use a boolean to keep track of whether or not the cell has been initialized, but I'd like to know if there's a cleaner way first.
This is easy enough to do from within a cell's implementation but there's no convenient way for a data source to differentiate newly created vs reused cells. If your configuration must be supplied by the data source then the data source probably need to check if the cell has been configured already.
The cells will be created once so you can use init or awakeFromNib to set some initial state. Cells will then have prepareForReuse called when being reused allowing you to perform any changes you need to make per-use.
The way I ended up solving this was to put my own view inside a generic UICollectionViewCell with a view tag. Then, when I go to deque my cell, I pull out the view using viewWithTag. If I get nil back, it's the first time this code has run, so I can init my view using my own constructor normally. This seemed slightly better than keeping track of a boolean in the cell implementation.

Load tableViewCell from Storyboard without using dequeueReusableCellWithIdentifier

I want to load a tableViewCell from the storyboard without using dequeueReusableCellWithIdentifier to create a prototype cell to reference before cellForRowAtIndex is called. Calling that outside of CellForRowAtIndex does funny stuff.
dequeueReusableCellWithIdentifier is still being used in cellForRowAtIndex as it normally has been.
I dynamically set the cell heights based on it's contents. This requires me to know where the size, positions, text attributes like font sizes, alignments, etc of views in the tableViewCell. Otherwise I have to hard code these values to match what's in the storyboard.
What I'm currently doing is create a new xib file with just the cell, load it from viewDidLoad, and keep a pointer to it.
-(void)viewDidLoad {
// typical coding stuff goes here
// load nib
UINib *nib = [UINib nibWithNibName:#"ContentTextCell" bundle:nil];
// assign nib to identifier
[self.tableView registerNib:nib forCellReuseIdentifier:#"ContentTextCell"];
// reference cell
NSArray *topLevelObjects = [nib instantiateWithOwner:nil options:nil];
_referenceContentTextCell = [topLevelObjects objectAtIndex:0];
}
Is there any way for me to load the tableview cell without make it's own nib? Using dequeueReusableCellWithIdentifier:forIndexPath: causes the tableView to behave in an incorrect way.
Additional notes
I think a lot of people are under the impression I call the code on cellForRowAtIndex. It's called in viewDidLoad. It was always displayed as such but perhaps it was easy to understand when skimming the question. I also still use dequeueResuableCell as normal in cellForRowAtIndex. Just wanted to make that clear.
The row heights are dynamic. If you made the suggestion that I should make the row height 44 then you may want to read the question more carefully before attempting to answer the question.
The text I'm using is from a json file, it requires the paragraph, font and positioning of a textView to calculate the text height, which impacts the row height. I'd like to pull these pieces of data from the prototype cell rather then hard coding the values, and making sure they match what's in the storyboard.
The code already works as is. It runs fine. I just think it'd be more convenient to be able to pull the prototype cell from the storyboard rather than making a new xib for it.
If I understand correctly, the row height is a function of your model and some attributes of subviews in the cell, for example, a string from your model and the font size in the cell's text view.
I agree that keeping the view attributes of the cell's subviews in code seems redundant with keeping them in the storyboard, but you're also right that keeping a reference cell around is weird. It's weird whether you get the cell from a nib or whether you find a way to get it from the storyboard (which I don't think you can, which is the answer to your stated question).
Dequeueing a cell in heightForRowAtIndexPath makes little more sense and probably causes an infinite recursive loop as I'm sure you've found.
So you probably won't love this answer, but I think best idea is "redundancy with an attitude change". "Redundancy" means that you keep the view attributes in code, like a method that returns the textView's desired font pointSize. "Attitude change", means you don't think of this as redundancy. Instead, your code should be the authority on all of the view attributes pertinent to row height. Think of the prototype cells in the storyboard as just a way of visualizing what the correct coded values should be. I'd even recommend setting the attributes in code using the coded values when you configure the cell, especially if there aren't too many of them.
Finally, if your rowHeight calculation is elaborate, and it sounds like it is, be sure to also implement
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
and do a much quicker calculation therein (like return a constant).
I've just been working through an almost identical problem. You want the height, but the height depends on a bunch of the cell UI setup. It might even be a fairly simple task of checking the padding height above and below an image. Something which could get tweaked in IB several times before you are done so you don't want to duplicate the padding value in code, you want to check them against the current values in IB.
You can call dequeueReusableCellWithIdentifier: from anywhere (assuming you have a reference to the UITableView). So you don't need another way to get the cell. This will not cause recursion or infinite loop problems.
There is a catch though. The cell won't go back to the auto-reuse pool. A UITableView figures out which cells scroll off the screen and puts them in the pool, but this cell never goes onto the screen and so the table view never remove it from the screen and put it back in the pool. To make matters worse, the table still has a strong reference to it; so if you lose your reference, it's not going to get cleaned up, it's essentially leaked memory. You can't use it, the table view can't use it and it will stay in memory until the backing UITableView gets deallocated.
I found a few ways around problem:
Dequeue the cell once, store it someplace safe and use the same one every time you need to test out some cell formatting. You can even call prepareForReuse: to clean it up every time you want to test something new. Holding a single extra cell in memory is unlikely to be a killer for most apps.
Sneak it back into the re-use pool. Wait, what? Yeah, I said you can't do it, but you can, but the thought makes me cringe a little. Next time you get to cellForRowAtIndexPath: don't dequeue a new cell, use the one you've got laying around and return that one instead. This will slip your wayward cell back into the fold and it will eventually make it's way back into the reuse pool.
So you can do this.... should you? Well, that's a different question. Apple has provided some alternatives to try and get around this issue, but in some cases they just don't work effectively.
That's a bad pattern and you will start to get undesired behaviours which you have already seen some of. It might be better to store the height against the cell as a class method.
+ (CGFloat)requiredHeight;
{
return 44.f;
}
and call it as such
self.tableView.rowHeight = [OKACell requiredHeight];
This does mean you need to manage the height in two places but because of the descriptive name and class method it shouldn't be difficult to change when that time comes.

UITableView initial row selection

Maybe I'm missing something obvious, but I'm have a hard time programmatically setting the row selection in a tableView. The goal is to simply have a tableView open with a row already selected. The problem appears to be that I have to wait until the tableView is fully loaded before I can modify the selection.
I've read various strategies such as calling reloadData for the tableView in the viewController's viewWillAppear method, then immediately calling selectRowAtIndexPath for the target row. But when I do that, I get a range exception because the tableView has zero rows at that point. The UITableViewDelegate methods (numberOfRowsInSection, etc.) don't appear to be called immediately in response to reloadData (which makes sense if the table rows are drawn "lazily").
The only way I've been able to get this to work is to call selectRowAtIndexPath after a short delay, but then you can see the tableView scroll the selected row into view.
Surely, there's a better way of doing this?
Well, you can use another strategy. You can create a hidden table view, configure how you want and than show to user. Use the tableview.hidden = YES.

Resources