I have developed a simple UITableView that displays a list of items. On top of this UITableView, I have created a selection bar in the form of a UIImageView that moves to whichever row is selected by the user. I have created two buttons (one up, one down) which also controls the movement of this selection bar.
When the user clicks the up button, the selection bar moves up exactly one row, and when the user clicks the down button, the selection bar moves down exactly one row. My problem is that when I reach the very top of the table, I want the selection bar to move to the very bottom of the table if the user clicks the up button, and I want the selection bar to go to the very top of the table if the user clicks the down button. Both buttons call the same method (I distinguish between the two buttons based on their tag values). However, when I do this, I am getting the following runtime exception:
2013-06-06 11:34:03.124 SimpleTable[4982:c07] *** Assertion failure in -[UITableViewRowData rectForRow:inSection:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableViewRowData.m:1630
2013-06-06 11:34:03.207 SimpleTable[4982:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for rect at invalid index path (<NSIndexPath 0x9489850> 2 indexes [0, 10])'
I am not sure why this is happening. Here is my relevant code which is called by my up and down buttons:
- (IBAction)buttonClicked:(id)sender {
if([sender tag] == 1){
if (_index.row == 0) {
_index = [NSIndexPath indexPathForRow:[_tableData count] inSection:_index.section];
}
else
_index = [NSIndexPath indexPathForRow:_index.row - 1 inSection:_index.section];
[UIView animateWithDuration:.3 animations:^{
CGRect rect = [self.view convertRect:[_table rectForRowAtIndexPath:_index] fromView:_table];
CGFloat floatx = _imageView.frame.origin.x - rect.origin.x;
_imageView.frame = CGRectMake(rect.origin.x + floatx, rect.origin.y, _imageView.frame.size.width, _imageView.frame.size.height);
}];
}
else if([sender tag] == 2){
if (_index.row == [_tableData count]) {
_index = [NSIndexPath indexPathForRow:0 inSection:_index.section];
}
else
_index = [NSIndexPath indexPathForRow:_index.row + 1 inSection:_index.section];
[UIView animateWithDuration:.3 animations:^{
CGRect rect = [self.view convertRect:[_table rectForRowAtIndexPath:_index] fromView:_table];
CGFloat floatx = _imageView.frame.origin.x - rect.origin.x;
_imageView.frame = CGRectMake(rect.origin.x + floatx, rect.origin.y, _imageView.frame.size.width, _imageView.frame.size.height);
}];
}
}
What am I doing wrong?
if (_index.row == [_tableData count])
Assuming _tableData
is the array that feeds your table, the count of the data in there will be one more than the row of your last index, since indexes are zero-based.
By this I mean, if there are 10 objects in your array, the last row is row 9.
So your check needs to be
if (_index.row + 1 == [_tableData count])
Instead.