How can I pass a parameter into a view in iOS?

匿名 (未验证) 提交于 2019-12-03 02:59:02

问题:

UIViewController *theController = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil]; [self.navigationController presentModalViewController: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?

回答1:

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]; 


回答2:

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]; 


回答3:

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]; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!