How can I pass a parameter into a view in iOS?
UIViewController *theController = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
[self.navigationController presentModalViewCont开发者_开发技巧roller:theController animated:TRUE];
Here's my code for showing my view. I know I can use app delegate variables, but it would be neater is I could pass a parameter in somehow, ideally using an enum. Is this possible?
Just create a new init method for your HelpViewController and then call its super init method from there...
In HelpViewController.h
typedef enum
{
PAGE1,
PAGE2,
PAGE3
} HelpPage;
@interface HelpViewController
{
HelpPage helpPage;
// ... other ivars
}
// ... other functions and properties
- (id)initWithNibName:(NSString*)nibName bundle:(NSBundle*)nibBundle onPage:(HelpPage)page;
@end
In HelpViewController.m
- (id)initWithNibName:(NSString*)nibName bundle:(NSBundle*)nibBundle onPage:(HelpPage)page
{
self = [super initWithNibName:nibName bundle:nibBundle];
if(self == nil)
{
return nil;
}
// Initialise help page
helpPage = page;
// ... and/or do other things that depend on the value of page
return self;
}
And to call it:
UIViewController *theController = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil onPage:PAGE1];
[self.navigationController presentModalViewController:theController animated:YES];
[theController release];
I generally just have certain variables in my UIView, which I set from the parent view. To pass variables back, I make use of the function:
[[[self.navigationController viewControllers] lastObject] setFoo:foo];
Define a setter for the parameter in HelpViewController
and change your code to:
HelpViewController *theController = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
[theController setSomeValue:@"fooBar"];
[self.navigationController presentModalViewController:theController animated:YES];
精彩评论