Objective-C: Is there any event when a Table Cell goes away? - iphone

Is there any message I can override called when a Table Cell goes away (on scrolling the table)?
I think it should be something like dealoc.
I'm asking this because I have below situation:
I have a table with many cells (100+) and each of this cell contains a ImageView. For loading the image (from a URL) I'm using NSOperationQueue/NSInvocationOperation. The problem appears when user is scrolling the table before the image is completely loaded: because I'm reusing the cells the image is displayed in wrong cell.
To avoid this I'm thinking to use "cancelAllOperations" of NSOperationQueue object when the cell goes away.
Note: I've tried but is not working if I call this message on "prepareForReuse".

iOS 6:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// Cancel operation here for cell at indexPath
}

Why not keeping the images in your table data source - the array that holds all the data for the table?
This way you won't have to load these images once again when scrolling back and it will solve your problem...

You can subclass UITableViewCell (or any UIView) and override willMoveToWindow:. It is called whenever the cell appears (or scrolls off screen).
When it goes out of the window the parameter will be nil:
- (void)willMoveToWindow:(UIWindow *)newWindow
{
[super willMoveToWindow:newWindow];
if (newWindow==nil) {
// Cell is no longer in window
}
}

If there were, it would be in the UITableViewDelegate class reference: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDelegate
The only thing they have is willDisplayCell which lets you do last minute adjustments BEFORE the cell appears. They don't have anything for when it disappears, but you could probably figure that out since there are only a certain number of cells on the screen at a time for a given cell height.
So if one is appearing and for a cell height of 80 for instance (in portrait mode so 480px screen height), then you can say that the one 6 cells away is about to disappear (6 cells * 80 pixels = 480). There are a couple other things to consider like which way you are scrolling, but you get the general idea.
Example Code: You should also look at lazy table loading via Apple's sample code http://developer.apple.com/iphone/library/samplecode/LazyTableImages/Introduction/Intro.html

I had the same issue and got some nice feedback in the developer forum. Quinn - The Eskimo from Apple:
As an aside, cancelling a network
small transfer because something has
scrolled off the screen is probably a
performance negative. For small
transfers, it's usually more efficient
to let it run to completion (and cache
the results in case they're needed in
the future). This is because of the
way that NSURLConnection manages HTTP
connection reuse. If you cancel a
transfer, NSURLConnection has to
either a) drop the underlying HTTP
connection on the floor, which means
it can't be reused, or b) continue
reading and just junk the data.
Neither of this is the best use of
resources.
Share and Enjoy
-- Quinn "The Eskimo!"
So, I'm not cancelling all the ImageDownload Operation, but rather only start them, when the user stops scrolling. Up to then only a placeholder is shown:
- (void)scrollViewWillBeginDragging:(UITableView *) tableView
{
self.dragging = TRUE;
}
- (void) scrollViewDidEndDragging: (UITableView *) tableView willDecelerate: (BOOL) decelerate
{
if(!decelerate && self.dragging)
[self loadThumbsForVisibleCells];
else
self.dragging = FALSE;
}
- (void) scrollViewDidEndDecelerating: (UITableView *) tableView
{
[self loadThumbsForVisibleCells];
}
Hope this helps!

Related

Pushing a view controller after scrolling is complete

When a user adds an item to my list, I want to scroll to the new row, highlight it, and select it (which will push a new controller). The key part is waiting for the scroll animation to complete before pushing the new controller.
In this answer, I learned how to use the animation delegate to wait until the scroll is complete.
However, if the insertion row is already on scree, the table view will not scroll and the method will not fire.
How can I wait to push the new controller until the end of the scroll, and deal with the case where no scroll will be initiated - and how might I tell the difference between each case?
The easiest way to check whether a given row is visible in your table view is something like this:
if (!CGRectContainsRect([self.tableView bounds], [self.tableView rectForRowAtIndexPath:indexPath])
{
// the row is partially outside the table view’s boundaries and needs to be scrolled for full visibility
}
else
{
// the row is within the boundaries and does not need to be scrolled
}
Try creating a method to see if scrolling is needed. If no scrolling is needed, call the push right away, otherwise wait for the delegate call and push.
- (BOOL)isSrollingingNeededForIndexPath:(NSIndexPath *)indexPath {
NSArray *visibleIndices = [self.tableView indexPathsForVisibleRows];
for (NSIndexPath *visibleIndexPath in visibleIndices)
if ([indexPath compare:visibleIndexPath] == NSOrderedSame)
return NO;
return YES;
}
Edit: Good point. Since indexPathsForVisibleRows is used for data rendering.
You could do essentially the same thing with indexPathsForRowsInRect where you use the content.offset.y and the tableview.frame.size.height to determine your "visible rect".
Then to account for partially visible rows at the top and bottom you could add rowHeight-1 to the top of the rect and subtract rowHeight - 1 from the bottom of the rect. Code shouldn't be too gnarly if you have static height rows. If you have varying height rows it would still work, but it would be a bit more involved.
All said though, it seems like a lot of code for something which you'd think would have a simple answer.

cellForRowAtIndexPath: not called

My app has two states: logged in and not logged in, and I have the following architecture (vastly simplified):
- ViewController A which contains a search box and a table view.
- ViewController B which is used for logging in the app.
The flow is the following:
- the user is not logged in;
- A is pushed on the stack. In viewWillAppear I check if the user is logged in and if yes, an async network request is being made and, once that is done, the table is loaded with the data from the network. However since the user is not logged in at this point, the table view is empty;
- the user taps on the search box; because he's not logged in, B is pushed (after a confirmation);
- he logs in successfully in B, then presses a button which pops B and shows A again;
- at this point in time, because he's logged in, from viewWillAppear I do the async request;
- when that is completed, I call reloadData on the table view.
What I notice is that numberOfRowsInSection: is called and it returns the correct result, however cellForRowAtIndexPath: is NOT called afterwards and the table remains empty.
I've checked and reloadData is called on the main thread.
Any idea what can it be? Cause it's driving me nuts!
Thanks,
S.
EDIT: Here's the async bit of code from viewWillAppear in A.
if ([User isLoggedIn]) {
[self.asyncRequest fetchDataWithCompletionHandler:^(id response, NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error) {
[Utils displayError:error];
} else {
self.array = response;
self.isLoaded = YES;
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointMake(0.0f, 0.0f) animated:NO];
}
}];
}
I've checked that the async request completes successfully and that response contains the correct data (this is the array used to back the UITableView).
After reloadData, I've put a breakpoint in tableView:numberOfRowsInSection: and it stops there and it returns the correct number of elements in array. After that, however, the breakpoint in tableView:cellForRowAtIndexPath: is never hit.
One valid scenario for why numberOfRowsInSection would be called but cellForRowAtIndexPath would not be called is when the size or positioning of the table does not require any rows to be displayed.
For example, let's say you had a table that was 20 pixels high, but the header for the first section was 30 high and you returned nil for the header (or did not implement viewForHeaderInSection). In this case, no rows would be displayed and it would look like the table just isn't there.
I see you are using IB. The sizing of the table can be deceptive in IB as it is assuming header and footer sizes. I would log the frame for the table so you understand where it is when the appliction is run (versus where it appears in IB). I would also be sure to manually size and position the table's frame before calling reloadData. This will solve this valid case where cellForRowAtIndexPath is not called.
Check that the numberOfSectionsInTableView is not returning 0.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
I had the exact same issue and the problem was that I was trying to call reloadData: from another thread. The solution would be:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
If you are using a different dataSource, as I was, make sure you are retaining the dataSource. Merely instantiating the class that will be the dataSource and assigning it via tableView.dataSource = myDataClass will not be sufficient as the dataSource property of a tableView is weak and will be released when viewDidLoad completes. All of the other methods were being called for me — even, surprisingly, heightForRowAtIndexPath — so this took me some time to debug.
If a Table View inside a view that conflicts something like Scrool View, it does not called. You should separate the views in your Storyboard or *.xib file.
// True
▼ View
► Table View
► Scrool View
► Constraints
// False
▼ View
► Scrool View
► Table View
► Constraints
// For others showing up on this questions via Google, etc.
// Check and make sure you've set the table view's data source and delegate.
self.tableView.dataSource = self;
self.tableView.delegate = self;
We had the same/similar issue. The code reached numberOfSections and numberOfRowsInSection (and it even returned values) but could not reach cellForRowAt. At the time, Table View in the Storyboard had only constraints for right side, left side and top, but not for bottom. Once we added constraint to the bottom, it worked like a charm.
So, check that you provide all needed constraints for the Table View.
If you are using auto layout like me and adding tableview to your view controller's view make sure you have added this line when you are allocating your table view.
tableView?.translatesAutoresizingMaskIntoConstraints = false
Silly mistake from my side.
Everyone keeps talking about height, but my TableView in a StackView with leading alignment ended up with 0 width.
Make sure to check if your TableView is correct size using Debug View Hierarchy.
I solved the problem because my Subview on which i added the UITableView was not allocated so it was returning nill and tableview was not calling cellForRowAtIndexPath but numberOfRowsInSection getting called
Wasted hours and then found out that my tableview was inside a stackview. As soon as I removed the stackview, it worked like a charm. For me it's Xcode 11.3 .
I am using a customer datasource and it was released. Because it is a weak reference of tableview.
This is embarrassing and perplexing, but here's my fix.
My code:
_scanResultTable.delegate = self;
_scanResultTable.dataSource = self; // self's lifecycle was fine, wasn't getting released
[_scanResultTable reloadData];
So the weird part is: the identifier _scanResultTable was never declared in my code, anywhere in the project. I have no idea how this compiled (and I recompiled several times).
My root cause was that I had linked my table output to scanResultTable in my ViewController, but was referring to it as _scanResultTable. Once I started using scanResultTable like I should've been, things cleared up. This makes me wonder if objective-c has something special about leading underscores in identifiers...
Edit: It does! Good lord I can't wait to never touch this language again.
In my case, I had the TableView inside a StackView. When I put it outside the StackView it worked.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Make sure self.data isn't nil!
// If it is, you'll always return 0 and therefore
// cellForRowAtIndexPath will never get called.
return [self.data count];
}
I'm using ReactiveCocoa. So I've created the model for table view. The data was prepared to be displayed, so numberOfRows and so on was called. But I haven't added the tableview as subview, thus cellForRowAtIndexPath was not called)))
This maybe too obvious but in my case i was deleting an element (Label) which was a reference to the top margin of my table programmatically, so it was not a problem with delegate/source but of the table having some problems with the content-size / height, this conflict created a weird behaviour, calling numberOfRowsInSection but not cellForRowAt indexPath
Are you sure that after the user logged in and B is popped the viewWillAppear method in A gets called in order to perform the refresh?
If you show B as a modal controller, when you dismiss it you won't have the viewWillAppear method called.
As far as I know, viewWillAppear/viewDidAppear (and other like it) are events generated by the UINavigationController in the case of navigation events (push/pop viewcontrollers).
So maybe that is why you eventually get your refresh when you leave A and return ... it all depends on the way to display the next viewcontroller.
Try to insert new rows manually instead of [self.tableView reloadData]:
[self.tableView beginUpdates];
for (int i = 0; i < responseArray.count; i++) {
_rowsNumber += 1;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
}
[self.tableView endUpdates];
In dataSource method return incremented int _rowsNumber:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _rowsNumber;
}
i solved same issue by checking tableViewCell identifier. Go To Attributes İnspector and look at identifier section. Probably is missing. So write cell identifier.
Same case here, but it was a mistake:
I included a Scrollview with 2 tablesViews inside a ViewController (design requirements), in the scrollview controller I created the ViewControllers (that contains the TableViews) programatically and I used a weak var to store it, bad idea because they were released at the end of viewDidLoad method.
If you don't see your tableview content, please, check if it was released.
My mistake was very brain-painful for me because all methods (delegate&datasource) were called except viewForCell...
I have same issue
i have use Table View inside the StackView and table view scroll disable and set height constrain but after that
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
Not working stop calling this method all Data Source and Delegate set properly.
if you have same issue than Solution is set Table View bottom , leading , trailing constrain
None of the answers here helped me.
I was using doing my constraints programmatically but forgot to write:
myTableView.translatesAutoresizingMaskIntoConstraints = false
Make sure your constraints are correct and none of them is removed at build time.

how to implement cyclic scrolling on tableview

Could you please help me with circular scrolling in tableview please.
I want that if I scroll down tableview, the rows should go in the reverse way --
it should appear that move back around (bottom rows go around and now come back down from the top) i.e, cyclic scrolling basically.
How can I do so. Any suggestions please.
Thanx in advance.
You could "fake" the cyclic scrolling repeating the same cells all over again. In the numberOfRowsInSection method, return n times the actual number of rows. Make sure n is big enough.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return numberOfActualRows*100;
}
Then in the cellForRowAtIndexPath method (and elsewhere) use the mod operator (%) to return the proper cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger actualRow = indexPath.row % numberOfActualRows;
...
}
You may want to hide the sroll indicator.
self.tableView.showsVerticalScrollIndicator = NO;
You may also want to scoll the table view to the middle before you display the table so scrolling backwards works fine.
[self.tableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow:[self tableView:self.tableView numberOfRowsInSection:0]/2 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
Of course, the user would eventually hit the bottom or the top if he/she kept scrolling over and over.
This question has already been asked: implementing a cyclic UITableView
I'm copying that answer here to make it easier because the asker hasn't ticked my answer.
UITableView is same as UIScrollView in scrollViewDidScroll method.
So, its easy to emulate infinite scrolling.
double the array so that head and tail are joined together to emulate circular table
use my following code to make user switch between 1st part of doubled table and 2nd part of doubled table when they tend to reach the start or the end of the table.
:
/* To emulate infinite scrolling...
The table data was doubled to join the head and tail: (suppose table had 1,2,3,4)
1 2 3 4|1 2 3 4 (actual data doubled)
---------------
1 2 3 4 5 6 7 8 (visualising joined table in eight parts)
When the user scrolls backwards to 1/8th of the joined table, user is actually at the 1/4th of actual data, so we scroll instantly (we take user) to the 5/8th of the joined table where the cells are exactly the same.
Similarly, when user scrolls to 6/8th of the table, we will scroll back to 2/8th where the cells are same. (I'm using 6/8th when 7/8th sound more logical because 6/8th is good for small tables.)
In simple words, when user reaches 1/4th of the first half of table, we scroll to 1/4th of the second half, when he reaches 2/4th of the second half of table, we scroll to the 2/4 of first half. This is done simply by subtracting OR adding half the length of the new/joined table.
Written and posted by Anup Kattel. Feel free to use this code. Please keep these comments if you don't mind.
*/
-(void)scrollViewDidScroll:(UIScrollView *)scrollView_
{
CGFloat currentOffsetX = scrollView_.contentOffset.x;
CGFloat currentOffSetY = scrollView_.contentOffset.y;
CGFloat contentHeight = scrollView_.contentSize.height;
if (currentOffSetY < (contentHeight / 8.0)) {
scrollView_.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY + (contentHeight/2)));
}
if (currentOffSetY > ((contentHeight * 6)/ 8.0)) {
scrollView_.contentOffset = CGPointMake(currentOffsetX,(currentOffSetY - (contentHeight/2)));
}
}
P.S. - I've used this code on one of my apps called NT Time Table (Lite). If you want the preview, you can check out the app: https://itunes.apple.com/au/app/nt-time-table-lite/id528213278?mt=8
If your table can sometimes be too short, at the beginning of the above method you can add a if logic to exit when data count is say for example less than 9.
I haven't done this myself, but you could try the approach you'd use with a UIScrollView to implement cycling scrolling of views (after all UITableView is a subclass of UIScrollView).
I would do as follows:
Create a UITableView with an arbitrary number of cells (at least 7 but will need more to prevent fast scrolling bumping at the end)
Position your UITableView so the centre cell is visible
Maintain a pointer to the index of the cell you are looking to display
In your cellForRowAtIndexPath: use your pointer to as an offset and add the row to it to get the cell that you want
When the UITableView has stopped moving (your UITableViewDelegate can serve as UIScrollViewDelegate so you can use scrollViewDidEndDecelerating). Set your offset index to the current cell, move the table view back to the centre cell without animation and reload the data.
The issue you will have is if the user keeps scrolling without stopping they will eventually hit the bumpers as the number of cells in the table is reached.
Hope this helps, and please post back if you get this working and it looks at all reasonable.
Regards
Dave
This is very much difficult to implement. However, take a look at the ScorllingMadness, which shows the demo of nested (cyclic) pages in a scroll-view.
You need to use the similar kind of trick here as UITableView is a subclass of UIScrollView.

Animate UITableViewCell height on selection [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can you animate a height change on a UITableViewCell when selected?
I've been doing a lot of Googling to try to figure out the correct way of doing this, and so far I am at a loss.
I have subclassed UITableViewCell with my own view and I am trying to animate the height of a UITableViewCell to expand when it is selected, and to contract when it is selected again. This table has the potential to contain thousands of rows, so I don't want to override the tableView's heightForRowAtIndexPath. Ideally I'd like to be able to have more than one cell expanded at a time, but that isn't as critical. What is the best way to do this?
Thank you,
Justin
There is no other mechanism for specifying cell height than heightForRowAtIndexPath. Unless you're properly accounting for the expanded cell in that method you're going to find your other cells either running over it or hidden under it. From boneheaded code where I forgot to set up heightForRowAtIndexPath, I'm pretty sure your other cells will be displayed over it.
Since you're talking thousands of rows, we'll assume the user can't rearrange the cells.
What you could do is store the expanded cell's index path when the user taps a given cell. Then, heightForRowAtIndexPath might look like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if ([indexPath isEqual:lastSelectedIndexPath])
{
return 80;
}
else {
return 44;
}
}
If you really want multiple selections, you could store the appropriate index paths to an array and check for them like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
CGFloat cellHeight = 44;
for (NSIndexPath *expandedIndexPath in expandedIndexPathsArray)
{
if ([indexPath compare:expandedIndexPath] == NSOrderedSame)
{
cellHeight = 80;
break;
}
}
return cellHeight;
}
Getting the animation to look right will take some work. I've toyed with this particular UI idea for awhile now and could never bring myself to sit down and really make it happen. One thing you could do is display a dummy view that animates while you're updating the tableview behind it.
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPathswithRowAnimation:(UITableViewRowAnimation)animation
could be of interest for this as you might be able to use the cell animations to simulate movement of the cells below to accommodate your expansion.
If you can forgo animating the cell's frame altogether, you could do an opacity animation of the expanded data once the new height has been set.
It's a toughie but if you make it work I bet it'll be pretty cool. Good luck.

Is there a better way to determine the right size for a UITableViewCell?

I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text).
SInce it appears that heightForRowAtIndexPath is called before I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height after I've laid out the text in the cell and have an idea of exactly what size it should be?
It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;)
Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort.
Note, you do not have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.
If the data is static, you can create a height table and cache the info.
if (0 == heightTable[index]) {
heightTable[index] = [self prepLayoutForCellAtIndex:index];
}
return (heightTable[index]);
Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.
I use the following, usually:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
UITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];
return cell.bounds.size.height;
}
Note that I use this for tables where I pre-cache a bunch of rows ahead of time, not for those with a LOT of cells. However, for things like Settings tables, where there are just a few rows, but most likely very differently sized, it works well. For larger tables, I do something along the lines of what Olie suggested.
If you look at SMS.app as example, Apple saves the row height of the cell in the SMS.app sqlite database.