Is it possible to refresh a single UITableViewCell in a UITableView? - objective-c
I have a custom UITableView using UITableViewCells.
Each UITableViewCell has 2 buttons. Clicking these buttons will change an image in a UIImageView within the cell.
Is it possible to refresh each cell separately to display the new image?
Any help is appreciated.
Once you have the indexPath of your cell, you can do something like:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
In Xcode 4.6 and higher:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:#[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
You can set whatever your like as animation effect, of course.
I tried just calling -[UITableView cellForRowAtIndexPath:], but that didn't work. But, the following works for me for example. I alloc and release the NSArray for tight memory management.
- (void)reloadRow0Section0 {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[indexPaths release];
}
Swift:
func updateCell(path:Int){
let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()
}
reloadRowsAtIndexPaths: is fine, but still will force UITableViewDelegate methods to fire.
The simplest approach I can imagine is:
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];
It's important to invoke your configureCell: implementation on main thread, as it wont work on non-UI thread (the same story with reloadData/reloadRowsAtIndexPaths:). Sometimes it might be helpful to add:
dispatch_async(dispatch_get_main_queue(), ^
{
[self configureCell:cell forIndexPath:indexPath];
});
It's also worth to avoid work that would be done outside of the currently visible view:
BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
....
}
If you are using custom TableViewCells, the generic
[self.tableView reloadData];
does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.
To successfully reload your first table view cell without switching views, use the following code:
//For iOS 5 and later
- (void)reloadTopCell {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):
- (void)refresh:(UIRefreshControl *)refreshControl {
//call to the method which will perform the function
[self reloadTopCell];
//finish refreshing
[refreshControl endRefreshing];
}
Now that you have that sorted, inside of your viewDidLoad add the following:
//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the
[self.tableView reloadData]; to your new refresh method.
If you wish to reload the data every time you switch views, implement the method:
//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
Swift 3 :
tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
Here is a UITableView extension with Swift 5:
import UIKit
extension UITableView
{
func updateRow(row: Int, section: Int = 0)
{
let indexPath = IndexPath(row: row, section: section)
self.beginUpdates()
self.reloadRows(at: [indexPath], with: .automatic)
self.endUpdates()
}
}
Call with
self.tableView.updateRow(row: 1)
Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = #[indexPath] for a single object, or Paths = #[indexPath1, indexPath2,...] for multiple objects.
Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)
Just thought I'd throw this into the mix. Hope it helps.
I need the upgrade cell but I want close the keyboard.
If I use
let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()
the keyboard disappear
Related
Dynamically loading UITableView with new rows
I have searched SO and have yet to come to a definitive answer. I have an app similar to Facebook and Instagram, where once you get to the bottom of the UITableView it calls a web service and loads another 25 rows of data. The problem I facing is that on loading the new 25 pieces, I am calling reloadData and this causes unpleasant UI flashing. What's the proper way of dynamically adding the new data to the UITableView as they scroll without the flashing (aka not calling reloadData?
After you add the new row items to your data source you need to use [tableView beginUpdates]; and [tableView endUpdates]; not reloadData. NSMutableArray *indexPathsToAdd = [NSMutableArray new]; for (Object *object in currentObjects) { if (![newObjects containsObject:object]) { int row = [currentObjects indexOfObject:object]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0]; [indexPathsToAdd addObject:indexPath]; } } [tableView beginUpdates]; [tableView insertRowsAtIndexPaths:indexPathsToAdd withRowAnimation:UITableViewRowAnimationAutomatic]; [tableView endUpdates];
Keep selected cell on heavily reloadRowsAtIndexPaths UITableView
In one of the views there is a UITableView which is getting updated rather often. Tracking the changes are done in a classic way using "reloadRowsAtIndexPaths" -(void)refreshCells:(NSArray *)changedCells { NSLog(#"refreshCells %i",[changedCells count]); [TableView beginUpdates]; [TableView reloadRowsAtIndexPaths:changedCells withRowAnimation:UITableViewRowAnimationBottom]; [TableView endUpdates]; } Question: How can I preserve the user's last selected Cell. the cell position may change after each update refreshCells?
You can save the current selection with NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow]; before the reload and select it again with if (selectedRow) { [self.tableView selectRowAtIndexPath:selectedRow animated:NO scrollPosition:UITableViewScrollPositionNone]; } after the reload. The cell position does not change unless you call insertRowsAtIndexPaths: or deleteRowsAtIndexPaths:.
iOS UItableview scrollToRowAtIndexPath not working anymore
This morning I just installed new Xcode which includes iOS 6. I have a table view loaded with a plist file containing chapters and lines. Chapters define the sections. The user selects chapter and line and the tableview is automatically scrolled to the correct position (in the viewDidLoad). NSIndexPath *indexPath = [NSIndexPath indexPathForRow:linePos inSection:chapterPos]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; this works just great in iOS5 simulator. Trying this in the iOS 6 simulator the scroll is not performed. I get no errors. I have checked, linePos and chapterPos receive correct values but the scroll is not performed. Any ideas why ?
Objective-C: [self.tableView reloadData]; dispatch_async(dispatch_get_main_queue(), ^{ NSIndexPath *rowIndexPath = [NSIndexPath indexPathForRow:3 inSection:0]; [self.tableView scrollToRowAtIndexPath:rowIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; }); Swift: tableView.reloadData() DispatchQueue.main.async { let indexPath = IndexPath(row: linePos, section: chapterPos) self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) }
For recent versions of iOS, please read Fyodor Volchyok's answer. Note that it's not marked as the accepted answer simply because at the time the question was first asked (Sept. 2012), the current answer was the working solution. More recent versions of iOS also got the same problem which is now solved by Fyodor Volchyok's answer, so you should +1 his answer at that moment. I found the answer. I have to first reload the data in the tableview NSIndexPath *indexPath = [NSIndexPath indexPathForRow:linePos inSection:chapterPos]; [self.tableView reloadData]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; Even though I found the answer I don't know why it is working in iOS5 and not in iOS6. EDIT Perhaps I should add that even though it was working, I was still having a problem in displaying the last row and posted a question for that UItableview scrollToRowAtIndexPath not displaying last row correctly As #Raj also asked for it, I should say that I was triggering that in the viewDidLoad. To correct the problem of the last row not displaying correctly I had to put it in the viewDidAppear.
This works in iOS 12 and 13: DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.tableView.scrollToRow(at: IndexPath(row: 0, section: 1), at: .bottom, animated: true) }
I ran into another issue (probably a bug) with scrollToRowAtIndexPath specifically on an iPhone X running ios11. My table has a few hundred sections and in collapsed mode ~10 would fit in the visible screen. As the indexPath got deeper, the scrolling gradually fell behind. For example, when I wanted the search to find the item in row 30, the ScrollPositionTop would have one additional row before the actual row I expect to be at the top. And as I tested searching for deeper rows, it started falling behind even more where for say anything past 100 rows deep or so, the expected row did not even come in the visible area. The workaround I found so far is to say animated:NO for the scrolling within dispatch_async, then it works without any glitches.
I'm adding this answer as an addition to Fyodor Volchyok's answer. I also found that dispatching solves the issue. I was able to find a workaround that doesn't dispatch. self.tableView.reloadData() let index = // the desired index path // For some reason, requesting the cell prior to // scrolling was enough to workaround the issue. self.tableView.cellForRowAtIndexPath(index) self.tableView.scrollToRowAtIndexPath(index, atScrollPosition: .Top, animated: false)
After iOS7 the property automaticallyAdjustsScrollViewInsets of UIViewController default is YES. It will cause system to adjust the contentOffset of tableView when the view controller pushed. Even you call [self.tableView scrollToRowAtIndexPath:rowIndexPath atScrollPosition:UITableViewScrollPositionNone animated:NO]; in the viewWillAppear. The contentOffset also will be changed by system after viewWillAppear. So my solution is: - (void)viewDidLoad { [super viewDidLoad]; self.automaticallyAdjustsScrollViewInsets = NO; /// any other codes } - (void)viewWillLayoutSubviews { self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, 0, 0); } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // change tableView data source [self.tableView reloadData]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.dataSourceArray count] - 1 inSection:0]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO]; }
One more possible workaround is to call layoutIfNeeded before calling scrollToRowAtIndexPath. [self.view layoutIfNeeded]; [self.tableView scrollToRowAtIndexPath...];
It worked for me in ios11 self.tableView.estimatedRowHeight = 0; self.tableView.estimatedSectionFooterHeight = 0; self.tableView.estimatedSectionHeaderHeight = 0 dispatch_async(dispatch_get_main_queue(), ^{ NSInteger numberOfSections = self.tableView.numberOfSections; if (numberOfSections > 0) { NSInteger lastSection = numberOfSections - 1; NSInteger lastRowInLastSections = [self.tableView numberOfRowsInSection:lastSection] - 1; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lastRowInLastSections inSection:lastSection]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:isAnimated]; } });
Fyodor Volchyok's answer in Swift: tableView.reloadData() let indexPath = NSIndexPath(forRow: linePos, inSection: chapterPos) // make sure the scroll is done after data reload was finished dispatch_async(dispatch_get_main_queue()) { self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) }
How can I check if a reuse identifier has been registered with a UITableView already?
In iOS apps, we have to register nib files with our table view before we can use UITableView#dequeueReusableCellWithIdentifier. Example: static NSString *myReuseIdentifier = #"MyReuseIdentifier"; UINib *cellNib = [UINib nibWithNibName:myReuseIdentifier bundle:nil]; [self.tableView registerNib:cellNib forCellReuseIdentifier:myReuseIdentifier]; Is there a way to check if a Nib has already been registered with a UITableView? I have a custom cell that I use in various tables across several controllers in my app. I'd like to move some of the code to a macro. Something like -(CustomCell *)customCell:(UITableView *)tableView { static NSString *reuseIdentifier = #"MyReuseIdentifier"; if (![table hasAlreadyRegisteredNib:reuseIdentifier]){ UINib *cellNib = [UINib nibWithNibName:reuseIdentifier bundle:nil]; [self.tableView registerNib:cellNib forCellReuseIdentifier:reuseIdentifier]; } CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; return cell; }
I am not sure if it that what you intend, but -dequeueReusableCellWithIdentifier: returns nil if the cell is not ready to reuse. Otherwise, it returns the cell, so you can simply try.
I believe the point of registerNib:forCellReuseIdentifier: is to reduce boilerplate code. Could you simply call this once in your viewDidLoad method?
UITableViewController canceling Edit mode animation when calling [table reloadData] inside (void)setEditing
I'm having a little problem: i made my setEditing method: - (void)setEditing:(BOOL)editing animated:(BOOL)animate { [super setEditing:editing animated:animate]; [mainTableView reloadData]; } i'm using the reloadData to call: cellForRowAtIndexPath, and then, if the table is in edit mode, i'll change the appearance of my cell (hiding some labels, for example); The problem is when i call [mainTableView reloadData] the Edit animation (the red circle slides from left to right and my cell slides to the right) doesn't exist. If don't call it, everything works ok, but i can't customize my cell, since cellForRowAtIndexPath is not called again. Any suggestion to make it work ?? Thanks!
Maybe you will try to update your table with [tableView beginUpdates] and [tableView endUpdates]? Do you need to reload all the cells or only some of them? EDIT: Here's the code for reloading all the cells: [tableView beginUpdates]; NSMutableArray *updatedPaths = [NSMutableArray array]; for (NSNumber *row in yourArray) { NSIndexPath *updatedPath = [NSIndexPath indexPathForRow:[row intValue] inSection:0]; [updatedPaths addObject:updatedPath]; } [tableView reloadRowsAtIndexPaths:updatedPaths withRowAnimation:UITableViewRowAnimationFade]; [tableView endUpdates]; yourArray is NSArray instance where you store your cell.textLabel values or something like that...