How can I tell if a UITableView contains a specific NSIndexPath?
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
}
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)
}
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)
}
}