iPhone UITableView trigger a parent method?
Okay, so I'm working on an iPhone app with a preferences-esque section where there's a base TableView, which has one section, and several rows of customized cells to hold a name and a value label. Clicking on a row brings up another View, which allows the user to pick from a list (another TableView), and select an item.
All of these TableViews are done programatically. The base TableView has a property that holds a Controller instance for each of the "pick from the list" Views. Each of the "pick from the list" views has a property called chosenValue
that has the currently-selected option. I've gotten the UI to handle the didSelectRowAtIndexPath
to update the chosenValue
property and then "pop
" the view (going back to the main TableView). But, even though the main TableView's cellForRowAtIndexPath开发者_如何学JAVA
method references the chosenValue
property of the subview that's held in a property, the view doesn't update when an item is selected. In short, how can the sub-view trigger a reloadData
on the parent object, after it "pops" and unloads?
You could realize this using the notifications or delegation, for example.
Using notifications your first view controller has to register for a notification like this:
…
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(methodToBeCalled:)
name:@"myNotification"
object:nil];
…
- (void)methodToBeCalled:(NSNotification *)notification {
[self.tableView reloadData];
// do something else
}
Then you can raise a notification in your second view controller like this:
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:nil];
Using delegation you could implement a property for a delegate on the second view, set that to self
before pushing the second view controller and call a method on the delegate when needed.
You should define a delegate for that. In the child TableView define a protocol:
@protocol ChildViewControllerDelegate
- (void) somethingUpdated;
@end
Also define a property for a delegate implementing this protocol:
id <ChildViewControllerDelegate> delegate;
Then in Parent all you need to do is to define a method somethingUpdated, assign itself (parent) to a delegate property in Child and call this method in Child view when you need to update it. Implementation of somethingUpdated in Parent can be different based on what you're trying to accomplish.
flohei thanks so much for posting this!! I got it working with NSNotificationCenter! I have a child view calling a method in a parent view now! Awesome. @sha I tried your protocol way also but could not figure it out. Perhaps a more illaborate discription would help a noob like me. I have been reading that your protocol way is the better cause I guess less code? So i'll try to keep learning it. Thanks to you both!
精彩评论