Search code examples
iphoneobjective-ciosxcodecocoa-touch

How can I tell if a UITableView contains a specific NSIndexPath?


Here is the code I'm using:

if (appDelegate.currentMainIndexPath != nil /* && doesPathExistInTableView */)
{
    [tblView scrollToRowAtIndexPath:appDelegate.currentMainIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    appDelegate.currentMainIndexPath = nil;
}

Solution

  • 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)
        }
    }