Here is the code I\'m using:
if (appDelegate.currentMainIndexPath != nil /* && doesPathExistInTableView */)
{
[tblView scrollToRowAtIndexPath:appDele
I iterated upon Kamran's answer:
+ (BOOL)isIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView {
if (!indexPath) {
return NO;
}
if (indexPath.section < [tableView numberOfSections]) {
if (indexPath.row < [tableView numberOfRowsInSection:indexPath.section]) {
return YES;
}
}
return NO;
}
You could try to get UITableViewCell
by :
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
// returns nil if cell is not visible or index path is out of range
here's the complete code :
UITableViewCell *cell = [cellForRowAtIndexPath:appDelegate.currentMainIndexPath];
if (appDelegate.currentMainIndexPath != nil && cell !=nil)
{
[tblView scrollToRowAtIndexPath:appDelegate.currentMainIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
appDelegate.currentMainIndexPath = nil;
}
A Swift adaptation of Kamran Khan's answer:
extension UITableView {
func hasRowAtIndexPath(indexPath: NSIndexPath) -> Bool {
return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRowsInSection(indexPath.section)
}
}
Swift 4:
extension UITableView {
func hasRow(at indexPath: IndexPath) -> Bool {
return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
}
}
There is a more convenient method to tell if a indexPath is valid:
For Swift 3.0:
open func rectForRow(at indexPath: IndexPath) -> CGRect
For Objective-C
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;
You will get CGRectZero if the indexPath is invalid.
func isIndexPathValid(indexPath: IndexPath) -> Bool {
return !tableView.rectForRow(at: indexPath).equalTo(CGRect.zero)
}
If you mean, 'is there a cell at index n' then you just have to compare the size of you datasource to n
if (appDelegate.currentMainIndexPath != nil [datasource count] > n)
{
[tblView scrollToRowAtIndexPath:appDelegate.currentMainIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
appDelegate.currentMainIndexPath = nil;
}
Where datasource is for instance an NSArray.
You can use this. Pass it indexpath's row and section
Objective C:
-(BOOL) isRowPresentInTableView:(int)row withSection:(int)section
{
if(section < [self.tableView numberOfSections])
{
if(row < [self.tableView numberOfRowsInSection:section])
{
return YES;
}
}
return NO;
}
Swift 3:
func isRowPresentInTableView(indexPath: IndexPath) -> Bool{
if indexPath.section < tableView.numberOfSections{
if indexPath.row < tableView.numberOfRows(inSection: indexPath.section){
return true
}
}
return false
}