Skip to content

Instantly share code, notes, and snippets.

@acefsm
Created May 16, 2017 19:57
Show Gist options
  • Save acefsm/37d51427a2ea7e35bab9d6396e1c2059 to your computer and use it in GitHub Desktop.
Save acefsm/37d51427a2ea7e35bab9d6396e1c2059 to your computer and use it in GitHub Desktop.
IndexPathWithOffset
NSIndexPath *IndexPathWithOffset(UITableView *tableView, NSIndexPath *indexPath, NSInteger offset)
{
if (indexPath.row < 0 || indexPath.section < 0)
{
return nil;
}
if (offset == 0)
{
return indexPath;
}
NSIndexPath *result = nil;
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
NSInteger restOffset = offset;
for (; section >= 0 && section < tableView.numberOfSections; offset > 0 ? ++section : --section)
{
NSInteger numberOfRows = [tableView numberOfRowsInSection:section];
NSInteger newRow = row + restOffset;
if (newRow >= 0 && newRow < numberOfRows)
{
result = [NSIndexPath indexPathForRow:newRow inSection:section];
break;
}
if (offset > 0)
{
restOffset -= numberOfRows - row;
row = 0;
}
else
{
restOffset += row + 1;
if (section > 0)
{
row = [tableView numberOfRowsInSection:section - 1] - 1;
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment