strange situation of UITableView when I want to scroll it - iphone

I'm building an easy app for chatting, each time I type in a sentence, the sentences is added into an array(which used to load the table view in cellForRowAtIndexPath delegate method), then I reload the table view. At last I use the following code to scroll the table view to the bottom
if ([self.chatList numberOfRowsInSection:0] != 0) {
NSUInteger rowCount = [self.chatArray count];
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
[self.chatList scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
however, the table view sometimes performs well, sometimes only scrolls to the second to the last line……

Try changing the scrollPosition to UITableViewScrollPositionBottom.

Related

Change an image in a UITableViewCell without reloading cell

I'm writing an iPhone app with a UITableView as the primary user interface. Each section consists of two rows, a header and the body. When the user clicks on the header, I remove the second row by changing the numberOfRowsInSection value:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
cbwComponent *comp = [_componentController objectInListAtIndex:section];
if([comp hasContentsView] && !comp.contentsHidden){
return 2;
}else
return 1;
}
When the user selects the header, I'm using the following code:
comp.contentsHidden = YES;
[self.tableView beginUpdates];
NSArray *deleteIndexPaths = [[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:1 inSection:indexPath.section], nil];
[self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
It's working great, with a nice smooth fade effect. The problem is, I'm trying to add an indicator in the header cell (row 0) that changes when it's clicked on. To change that image I have to refresh the top row as well as the second row, which makes the transition look bad (well, not nearly as smooth). Is there a way to change the image in a UITableViewCell without refreshing the cell?
Thanks
EDIT: I figured it out! You can maintain the smooth transition as long as you reload that first row before you make the change to the second row. It has to be called inside of [tableView beginUpdates];
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:0 inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
...
[self.tableView endUpdates];
Did the trick.
You could also subclass a tableview cell and implement a view transition in it that can be called from your view controller. You could then call that without having to reload the cell.
[(YourCustomCell*)[tableView cellForRowAtIndexPath:indexPathOfYourCell] fadeInIndicator];

How to create a toolbar between UITableView rows

I am interested on how tweetbot does the following:
I would like to create the same thing with my app, where if you click on a row, it pops
an additional UIToolBar and pressing on any other row will dismiss this view with animations.
The logic I think is simple, you just need to add a subView to the UITableViewCell when pressed and shift the rest of the content up, but how do you actually dismiss it when I press the other row?
The best way to do this is to add a dummy cell below the cell that was tapped.
First you need to keep track of what cell is been tapped and act accordingly.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//if user tapped the same row twice let's start getting rid of the control cell
if([indexPath isEqual:self.tappedIndexPath]){
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
//update the indexpath if needed... I explain this below
indexPath = [self modelIndexPathforIndexPath:indexPath];
//pointer to delete the control cell
NSIndexPath *indexPathToDelete = self.controlRowIndexPath;
//if in fact I tapped the same row twice lets clear our tapping trackers
if([indexPath isEqual:self.tappedIndexPath]){
self.tappedIndexPath = nil;
self.controlRowIndexPath = nil;
}
//otherwise let's update them appropriately
else{
self.tappedIndexPath = indexPath; //the row the user just tapped.
//Now I set the location of where I need to add the dummy cell
self.controlRowIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
}
//all logic is done, lets start updating the table
[tableView beginUpdates];
//lets delete the control cell, either the user tapped the same row twice or tapped another row
if(indexPathToDelete){
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathToDelete]
withRowAnimation:UITableViewRowAnimationNone];
}
//lets add the new control cell in the right place
if(self.controlRowIndexPath){
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:self.controlRowIndexPath]
withRowAnimation:UITableViewRowAnimationNone];
}
//and we are done...
[tableView endUpdates];
}
Whenever you have that dummy cell present you have to make sure to send the correct count.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.controlRowIndexPath){
return modelArray.count + 1;
}
return self.modelArray.count;
}
Also, return the appropriate height for your ControlCell.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath isEqual:self.controlRowIndexPath]){
return 45; //height for control cell
}
return 70; //height for every other cell
}
Lastly, remember the control cell is a dummy. Is not part of the model, thus you have to account for that. If the user taps a row that is above the last tapped row is ok but when the new tapped row is below that control cell you have to make sure you access the right row in your model. In other words, account for that fake cell in the middle of your view.
- (NSIndexPath *)modelIndexPathforIndexPath:(NSIndexPath *)indexPath
{
int whereIsTheControlRow = self.controlRowIndexPath.row;
if(self.controlRowIndexPath != nil && indexPath.row > whereIsTheControlRow)
return [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0];
return indexPath;
}
I hope this helps.
In tableView:didSelectRowAtIndexPath:, you remove the tool view from the last selected cell. If there is no such view, you create a new one. Then you add this view to the newly selected cell. Save the indexPath of the selected row.
In tableView:heightForRowAtIndexPath:, you check if the indexPath is the same as the saved indexPath. If they are equal, you return a height that is the height of both views. If it is not equal, just return the height of the "real cell".
Put all your calls in didSelectRowAtIndexPath between [tableView beginUpdates] and [tableView endUpdates] to get animation for the height change.
rjgonzo's code works fine except for the case where you only have 1 row in the tableview. When there's only 1 row (and 1 object in the tableview datamodel) you'll get an NSRange exception when you call insertRowsatIndexPath(s). To fix this I checked to see if the datamodel has only 1 object and if so then I add the row to the current indexpath (instead of the controlindexpath) which results in the row logically being added above the first row and then I call moveRowAtIndexPath to interchange the rows after calling [self.tableView endUpdates]. The animation shows as expected with the control row appearing to slide down from the 1st row.
if(self.controlRowIndexPath){
//Check to see if the datamodel only has 1 object
if([self.objects count]==1){
//If so then insert the row above the row
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationNone];
}
else
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:self.controlRowIndexPath]
withRowAnimation:UITableViewRowAnimationNone];
}
[self.tableView endUpdates];
//if the row was inserted above the 1st row then switch the rows
if([self.objects count]==1)
[self.tableView moveRowAtIndexPath:self.controlRowIndexPath toIndexPath:indexPath];
I would not add a subview to a UITableViewCell, I would add another row to the UITableView. That way, the UITableView will take care of the animation. (And I don't think that's possible to animated UITableViewCell height changes...)
Use simply
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
do add a row. And
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
to remove it.
#rjgonzo this works great but there is a minor issue on how you keep the indexPathToDelete. Since it's just another pointer to self.controlRowIndexPath, once you clear or reassign the self.controlRowIndexPath, indexPathToDelete will not be what you wanted, and tableView deleteRowsAtIndexPaths:withRowAnimation: call, you will get an SIGBART crash.
so, instead of
//pointer to delete the control cell
NSIndexPath *indexPathToDelete = self.controlRowIndexPath;
and
//lets delete the control cell, either the user tapped the same row twice or tapped another row
if(indexPathToDelete){
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathToDelete]
withRowAnimation:UITableViewRowAnimationNone];
}
the following code should work fine:
//pointer to delete the control cell
NSIndexPath *indexPathToDelete = [NSIndexPath indexPathForRow:self.control_row_index_path.row inSection:self.control_row_index_path.section];
...
...
//lets delete the control cell, either the user tapped the same row twice or tapped another row
if(indexPathToDelete.row != 0){
NSLog(#"row to delete %d", indexPathToDelete.row);
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathToDelete] withRowAnimation:UITableViewRowAnimationNone];
}
Here's what I'm doing to get the animation to be clean.
In addition to the strategy user fluchtpunkt suggests (that is, adding a subview to the cell, updating the cell height via heightForRowAtIndexPath, beginUpdates, and endUpdates), I'm finding the following measures to be helpful with the animation:
The tableviewcells have a background image. Otherwise, the added subview/toolbar is visible through the cell just before the tableview animates the height change.
The tableviewcell is 'behind' the view that is the cell below it, otherwise again the subview/toolbar will show too soon. I'm using [tableview sendSubviewToBack:cell]; and it's taking care of that.
This is clean for me, but not exactly like Tweetbot. Interestingly, Tweetbot's animation seems to pull the toolbar down as the bottom of the cell animates down. It seems like some additional animation must be taking place, or my conspiracy theory is that it is actually adding the subview to the top of the cell below the selected cell, and then performing the lengthening and animation on the cell below.

uitableview autoupadate while scrolling to top

I want to update Uitableview when it will be scroll to top. As in facebook app when we scroll uitableview to top it will show "upadating" and insert new rows in top of table view. I want to give same effect in my app. is it possible to design it using default uitableview methods or we need to customize it.
If anyone is having idea about it please please reply.
You may want to detect when your user scrolled to top:
Several ways to do this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.y == 0)
NSLog(#"At the top");
}
Source: How can I get scrollViewDidScrollToTop to work in a UITableView?
Or using:
scrollViewDidScrollToTop:
Source: http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/UIScrollView_pg/ScrollingViewContent/ScrollingViewContent.html
You can now fire your events depending on the user's actions:
i.e.
When user scrolled to top, call your UI change using, then call your update logic.
insertRowsAtIndexPaths:withRowAnimation:
Sample and Source: http://www.mlsite.net/blog/?p=466
After update logic has ended, call [tableView reloadData] assuming your datasource is now updated. Optionally you may want to make use of deleteRowsAtIndexPaths:withRowAnimation: to add effects when removing your cell notifying that you are currently updating.
Another way :
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
[self fetchMoreMessages];
}
}
You can use insertRowsAtIndexPaths: to insert new rows at the front of table view. For example,
NSIndexPath *indexPathForRow_0_0 = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath *indexPathForRow_0_1 = [NSIndexPath indexPathForRow:1 inSection:0];
[yourTableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathForRow_0_0, indexPathForRow_0_1, nil] withRowAnimation:UITableViewRowAnimationTop];
The above code inserts two rows at the index 0 and 1 in section 0.
Note: You need to customize your dataSource and delegate methods to adjust with these insertions. Important thing is you need to return the correct value from numberOfRowsInSection method. Here, in the above example, your numberOfRowsInSection method should return yourPreviousNumberOfRows + 2, because we added two rows here.

reloadRowsAtIndexPaths:withRowAnimation: crashes my app

I got a strange problem with my UITableView: I use reloadRowsAtIndexPaths:withRowAnimation: to reload some specific rows, but the app crashes with an seemingly unrelated exception: NSInternalInconsistencyException - Attempt to delete more rows than exist in section.
My code looks like follows:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
When I replace that reloadRowsAtIndexPaths:withRowAnimation: message with a simple reloadData, it works perfectly.
Any ideas?
The problem is that you probably changed the number of items of your UITableView's data source. For example, you have added or removed some elements from/to the array or dictionary used in your implementation of the UITableViewDataSource protocol.
In that case, when you call reloadData, your UITableView is completely reloaded including the number of sections and the number of rows.
But when you call reloadRowsAtIndexPaths:withRowAnimation: these parameters are not reloaded. That causes the next problem: when you are trying to reload some cell, the UITableView checks the size of the datasource and sees that it has been changed. That results in a crash. This method can be used only when you want to reload the content view of the cell (for example, label has changed or you want to change its size).
Now if you want to remove/add cells from/to a UITableView you should use next approach:
Inform the UITableView that its size will be changed by calling method beginUpdates.
Inform about inserting new row(s) using method - (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation.
Inform about removing row(s) using method - (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation.
Inform the UITableView that its size has been changed by calling the method endUpdates.
I think the following code might work:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
I had this problem which was being caused by a block calling reloadRowsAtIndexPaths:withRowAnimation: and a parallel thread calling reloadData.
The crash was due to reloadRowsAtIndexPaths:withRowAnimation finding an empty table even though I'd sanity checked numberOfRowsInSection & numberOfSections.
I took the attitude that I don't really care if it causes an exception. A visual corruption I could live with as a user of the App than have the whole app crash out.
Here's my solution to this which I'm happy to share and would welcome constructive criticism. If there's a better solution I'm keen to hear it?
- (void) safeCellUpdate: (NSUInteger) section withRow : (NSUInteger) row {
// It's important to invoke reloadRowsAtIndexPaths implementation on main thread, as it wont work on non-UI thread
dispatch_async(dispatch_get_main_queue(), ^{
NSUInteger lastSection = [self.tableView numberOfSections];
if (lastSection == 0) {
return;
}
lastSection -= 1;
if (section > lastSection) {
return;
}
NSUInteger lastRowNumber = [self.tableView numberOfRowsInSection:section];
if (lastRowNumber == 0) {
return;
}
lastRowNumber -= 1;
if (row > lastRowNumber) {
return;
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
#try {
if ([[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] == NSNotFound) {
// Cells not visible can be ignored
return;
}
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
#catch ( NSException *e ) {
// Don't really care if it doesn't work.
// It's just to refresh the view and if an exception occurs it's most likely that that is what's happening in parallel.
// Nothing needs done
return;
}
});
}
After many try, I found "reloadRowsAtIndexPaths" can be only used in certain places if only change the cell content not insert or delete cells. Not any place can use it, even you wrap it in
[self beginUpdates];
//reloadRowsAtIndexPaths
[self endUpdates];
The places I found that can use it are:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (IBAction) unwindToMealList: (UIStoryboardSegue *) sender
Any try from other places like call it from "viewDidLoad" or "viewDidAppear", either will not take effect (For the cell already loaded I mean, reload will not take effect) or cause exception.
So try to use "reloadRowsAtIndexPaths" only in those places.
You should check cell visibility before reload. Here is Swift 3 code:
let indexPath = IndexPath(row: offset, section: 0)
let isVisible = tableView.indexPathsForVisibleRows?.contains{$0 == indexPath}
if let v = isVisible, v == true {
tableView.reloadRows(at: [indexPath], with: .automatic)
}
I had the same issue. In my case; it was happening only if another view controller pop/pushed over existing table view controller and then[self.tableView reloadRowsAtIndexPaths] function is called.
reloadRowsAtIndexPaths call was hiding/showing different rows in a table view which is having over 30, visually complex, rows. As i try to fix the issue i found that if i slightly scroll the table view app wasn't crashing. Also it wasn't crashing if i don't hide a cell (by returning 0 as height)
To resolve the issue, i simply changed the "(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath" function and returned at least 0.01 as row height.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
return rowModel.height + 0.01; // Add 0.01 to work around the crash issue.
}
it solved the issue for me.
THIS IS OLD. DO NOT USE.
I just bumped into this issue when I was calling reloadRowsAtIndexPaths... in order to change the cell to an editing cell containing a UITextField. The error told me I was deleting all of the rows in the table. To solve the problem, I removed:
[self.tableView beginUpdates];
NSArray *reloadIndexPath = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:count inSection:section]];
[self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
and replaced it with
[self.tableView reloadData];
The app crashes because you have made some changes to your tableView. Either you have added or deleted some rows to the tableView. Hence when the view controller asks your model controller class for data, there is a mismatch in the indexPaths. Since the indexPaths have changed after modification.
So either you simply remove the call
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
or replace it with
[self.tableView reloadData];
Calling reloadData checks your number of sections, number of rows in each section and then reloads the whole thing.
If data count changes completely, then use reloadData else, there is three functions to do it.
When data count changes we use insertRows / deleteRows and when data count still the same use reloadRows.
Important! don't forget call beginUpdates and endUpdates between insertRows/deleteRows/reloadRows calls.

Scroll to cell then get subview

I have cells in a table with custom fields that allow entry of numbers using a custom numpad. That includes a tab. When tabbing from the bottom of the table to the top, I need to (i) scroll the table to the top and (ii) select the custom field in that table.
I'm finding that if I call cellForRowAtIndexPath directly after I've called scrollToRowAtIndexPath, the former returns a null cell. If called again, after the scroll has completed, the cell is returned as expected. I need the cell intself so I can get the custom view by tag value, and select it.
I have been trying to find a solution. One might be to insert a delay after the scroll to allow it to complete. But I've tried using performSlector:withObject:afterDelay without success.
This is my code called when the tab is pressed.
-(void) customDualViewTabbed:(CustomDualView *)dualView {
UITableViewCell *cell=(UITableViewCell*)([dualView superview].superview);
NSIndexPath *fromIndexPath=[self.tableView indexPathForCell:cell];
NSIndexPath *toIndexPath;
if ((fromIndexPath.row+1)<[self.tableView numberOfRowsInSection:fromIndexPath.section]){
toIndexPath = [NSIndexPath indexPathForRow:(fromIndexPath.row+1) inSection:fromIndexPath.section];
}
else {
toIndexPath = [NSIndexPath indexPathForRow:0 inSection:fromIndexPath.section];
[[self tableView] scrollToRowAtIndexPath:toIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
//get cell we tabbed to
cell=[self.tableView cellForRowAtIndexPath:toIndexPath];
CustomDualView *dualView2 =(CustomDualView *)[cell viewWithTag:dualView.tag];
[dualView2 setSelected:(SelectedState)SelectedLeftTabbed];
}
The cells in a UITableView are only loaded as needed. As a result, if the cell that you are scrolling to resides at an index that currently off-screen, you will get a nil response from cellForRowAtIndexPath.
Now, since UITableview conforms to the UIScrollViewDelegate protocol, you can implement those delegate methods in addition to the UITableViewDelegate methods. Implementing one that you know will be called when your cell is in view, like scrollViewDidEndDecelerating:, and then making your call to cellForRowAtIndexPath might do the trick.