How to delete a row from table view IOS - iphone

I want to delete a row from table view without using the below data source method. How to do it?
- (void) tableView : (UITableView *)tableView
commitEditingStyle : (UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath : (NSIndexPath *)indexPath

How about [UITableView deleteRowsAtIndexPaths: withRowAnimation:]?
(I've linked Apple's documentation linked for you).
#Scar's idea is also good, but that will refresh the entire table and that might be a bit disruptive to the user if they're scrolled to the bottom of the table and the refresh takes them to the top.

Not quite that simple, you have to do this atomically with a UITableView
[_tableView beginUpdates]; // <-- pretty important
long selectedRow = _tableView.selectedRow;
[_tableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:selectedRow] withAnimation:NSTableViewAnimationSlideUp];
//then remove your object from the array
[((NSMutableArray*) _searchResults) removeObjectAtIndex:selectedRow];
[_tableView endUpdates];
This prevents delegate methods from being called while the array is being updated.

Remove the row from your model and call -deleteRowsAtIndexPaths:withRowAnimation:.

Related

iOS - UITableView refresh table properly?

I have lots of data and lots of rows in my tableView.
when data changes I want to update my visible cells on the screen, I really don't want to use reloadData because it's an expensive call.
Is it possible to somehow update the visible cells only?
I tried calling : beginUpdate & endUpdate on the table, but that doesn't work all the time?
Any suggestions?
You can:
[tableView reloadRowsAtIndexPaths:[tableView indexPathsForVisibleRows]
withRowAnimation:UITableViewRowAnimationNone];
For Swift 3:
tableView.reloadRows(at: tableView.indexPathsForVisibleRows!, with: .none)
Try calling 'deleteRowsAtIndexPaths', a method of UITableView, right after you delete the model from your data source. For example, if you are deleting a row in editing mode, you could write something like the code below. Note that the first line in the 'if' statement removes the object from the data source, and the second line cleans up the table:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( editingStyle == UITableViewCellEditingStyleDelete ) {
[[[[[ItemsStore sharedStore] parameterArray] objectAtIndex:indexPath.section] objectForKey:#"data"] removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}

Objective C, How to load more data when user tries to scroll up at the bottom row of the tableview

I have UITableView and I want to load more data when user tries to scroll up at the bottom row of the tableview just like iPhone email application...What is the best way for this?
Implement the Delegate for UIScrollView and detect at which point where you want to load more data.
Or You can put the update code in the "cellForRowAtIndexPath:" method, here detect the row, say 100 and append the data, and remove the data in row <100 , you will have to check for dataSource's count before updating.
Append new contents to the Data Source (Array) and do this:
[self.tableView reloadData];
I tried adding this in UITableViewDelegate method "willDisplayCell"
(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == floatRows - 1) {
floatRows += 10;
[tableView reloadData];
}
}
It is keep loading another 10 for every scroll to bottom.
Not sure, it will work for you.

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.

How do I select a UITableViewCell by default?

I have created a UITableView and would like a specific UITableViewCell to appear selected (blue) when the view is loaded.
-(void)viewWillAppear:(BOOL)animated {
// assuming you had the table view wired to IBOutlet myTableView
// and that you wanted to select the first item in the first section
[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
animated:NO
scrollPosition:UITableViewScrollPositionTop];
}
I'm using this technique to select one of two UITableViewCells so the users knows which cell a UIDatePicker below the table view it will effect. This technique is used by Apple in the calendar app when you create a new event and set the dates.
Be judicious using this method, as selecting the row in this way is something Apple suggests against doing to show a "chosen" state.
Instead, consider setting the cell's accessoryType property to something like UITableViewCellAccessoryCheckmark.
You should put it in viewWillAppear.
[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
animated:NO
scrollPosition:0];
If you try to select it in cellForRowAtIndexPath:, then it will not take the required style.
Definitely watch out. I'm sure you have a good reason, but look closely at the Human Interface Guidelines document Apple provides. Apps get rejected for not unselecting table rows. I'd encourage you to find the appropriate section of the HIG and see Apple offers any suggestions.
Use this code to select cell by default in table view, indexPath can be vary according to your need
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
[theTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
}
Use the UITableViewCell method
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
Info here.
Sometimes, when you're not in a UIViewController, you have no viewWillAppear, and sometimes, you created your UITableView programmatically.
The easy solution is to implement this delegate method:
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.selectedIndex == indexPath.row) {
cell.selected = YES;
}
}
It's does not work in the cellForRowAtIndexPath because the cell is not yet displayed. and the setSelected method is called just when this one is displayed.