I am trying to implement a view similar to that of Apple's calendar application's setting the start time and end time view. I have the view looking great, but I am running into two problems. First, I want to have the first row selected automatically. I sort of have this working using:
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
[dateTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
However, an animation shows, visually selecting the rown when the view is loaded, I want it to already be selected when the view loads.
The second, and much more important, problem is that when I reload the data after the picker has updated I lose the selection, and my task simply doesn't work.
Now I know this is the default action of reloadData, I am looking for an alternative method to accomplish my goal, or perhaps how I can augment reloadData to not deselect the current selection.
My task is included below:
-(IBAction)dateChanged
{
NSIndexPath *index = self.dateTableView.indexPathForSelectedRow;
if(index == 0)
{
if (self.date2 == plusOne ) {
self.date = [datePicker date];
plusOne = [self.date dateByAddingTimeInterval:60*60];
self.date2 = plusOne;
}
else
{
self.date = [datePicker date];
}
}
else{
self.date2 = [datePicker date];
}
[dateTableView reloadData];
}
Note: plusOne is a variable that initially indicates an hour from the current time.
Thanks in advance!
For the first problem, set animated:NO on the method call. You are currently setting it to YES.
[dateTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionBottom];
For the second problem, it's not really clear what you are trying to select after reloading the data, but I see a problem with this line:
if(index == 0)
You are asking if the pointer to the object is 0. I think what you want is either to check that index == nil
or that index.section == 0 && index.row == 0
or something like that.
Anyway, if you call reloadData
on the UITableView, you're going to lose the selection. At that point, you need to select a new row. If there is an item in your data model that you want to select, you need to figure out where it is and select it based on where it will be in the table (You should know this because you are providing that information in the UITableViewDataSource delegate methods.). Alternatively, if you want to select the NSIndexPath you saved in the first line of dateChanged
, just select it after reloading the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With