I_Catch_Nothing
I_Catch_Nothing

Reputation: 17

Stop [tableView loadData] from deselecting row using Xcode 5 with UIViewController

Here is my program. I want to create a simple list of items that display a number. When the rows are tapped the number will increment by one.

EDIT: Is it proper to change the UI of a row in the didSelectRowAtIndexPath function?

I created a UIViewController in Xcode 5 through a storyboard and it does everything right except I can't seem to stop the [tableView reloadData] from deselecting my row after being tapped. Specifically, I want the row to turn gray and then fade out normally.

I have tried selecting the row and then deselecting the row programatically after calling [tableView reloadData], but it doesn't work.

I know that if I was using UITableViewController that I could just call [self setClearsSelectionOnViewWillAppear:NO], but I'm not.

Is there a similar property I can set for UIViewController?

Here is the code:

    [tableView beginUpdates];
    [counts replaceObjectAtIndex: row withObject: [NSNumber numberWithInt:newCount]];
    [tableView reloadData];
    [tableView endUpdates];

I feel I may not be describing what is going on. I have a row that uses UITableViewCellStyle2, which displays a label to the left and right. On the right aligned text is a number that increments each time the row is tapped. Simply updating the data structure does not solve the problem. I need to update it visually. I don't need or want to replace the row, unless I have too. I just want to update the right-aligned text field AND keep the row from being deselected immediately without animation. I can do one or the other, but not both.

Is there a way to just update the right-aligned text field while still staying true to the MVC model?

Upvotes: 0

Views: 248

Answers (1)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

Remove the [tableView reloadData]; from the code. It should not be called in the methods that insert or delete rows, especially within an animation block implemented with calls to beginUpdates and endUpdates .

Call reloadData method to reload all the data that is used to construct the table, including cells, section headers and footers, index arrays, and so on. For efficiency, the table view redisplays only those rows that are visible. It adjusts offsets if the table shrinks as a result of the reload. The table view's delegate or data source calls this method when it wants the table view to completely reload its data.

[tableView beginUpdates];
[counts replaceObjectAtIndex: row withObject: [NSNumber numberWithInt:newCount]];
[tableView endUpdates];

See the developer.apple section - reloadData

If you want to keep the selection after reload, the easy way is

NSIndexPath *selectedRowIndexPath = [tableView indexPathForSelectedRow];
[tableView reloadData];
[tableView selectRowAtIndexPath:selectedRowIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];

Upvotes: 2

Related Questions