views:

31

answers:

2

Is there a way to know when the index on uitableview is actually used? I can’t find any methods in the Apple documentation, but I was wondering if anyone else knows anything. I would basically like to make an animation in my table view that changes depending on what section is selected in the index, and I have no idea how to do this without accessing the table view index.

Any help is greatly appreciated.

Thanks.

A: 

Not a very elegant solution, but you may be able to subclass UITableView and watch for it in - (void)didAddSubview:(UIView *)subview; when it first shows up. This assumes that it is added directly to the UITableView and not one of its subviews or superview, and that you can recognize the added view as the index. It is also possible that after the first time it is added it will be hidden and shown instead of being removed and added again.

drawnonward
A: 
  1. The UITableViewDataSource delegate method -tableView:sectionForSectionIndexTitle:atIndex: returns an NSInteger representing the section selected from the section index. Override this method in whichever class is your data source delegate (probably your table view controller).

  2. Set up a property in the view controller, an NSInteger called selectedSectionIndex. Its value is set within the aforementioned delegate method.

  3. Finally, set up an observer in the view controller, which waits for changes to this property and triggers your desired code when a change does get observed.

In your -viewWillAppear: method, for example:

[self addObserver:self forKeyPath:@"selectedSectionIndex" options:NSKeyValueObservingOptionNew context:nil];

In your -viewWillDisappear: method, unregister the observer:

[self removeObserver:self forKeyPath:@"selectedSectionIndex"];

It's important to do this so that the -dealloc method doesn't throw an exception.

Finally, set up the observer method to do something when there is a change to selectedSectionIndex:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"selectedSectionIndex"]) { 
        // The section index changed, so trigger some cool animation
    }
}

The Key-Value Observing pattern is a good, general way to trigger something when an object's value changes somewhere. Apple has written a good "quick-start" document that introduces this topic.

Alex Reynolds
Thank you very much, this seem to be exactly what I’m looking for.
Michaeljvdw