2012-07-11 70 views
0

在我的应用程序中,我有一个ViewController(ViewController 1),它有一个UITextField和一个UIButton。在我的ViewController 2中,我有一个UINavigationBar。我希望能够在ViewController 1文本框中输入内容,按下按钮,然后将ViewController 2中的UINavigationBar文本设置为ViewController 1中的UITextField。但是当然,Xcode不会让您从另一个ViewController中声明对象,而无需做更多的工作。我怎样才能做到这一点?声明来自不同ViewController的对象

回答

0

你的问题重刑是不是很清楚,但从我能理解你想要一个ViewControllerUIButton设置NavigationBar的第二个标题ViewController

似乎对我来说很奇怪的行为,但这是我认为可能会帮助你。

关于你的第ViewController创建一个协议/委托功能,以便当按下你UIButton您可以拨打:

-(IBAction) changeTitle:(id) sender {  
[self.delegate buttonPressed:txtView.text]; 
} 

有了这样的发送您的UITextField的文字到您AppDelegate,或谁创建这两个ViewControllers,然后您将收到该文本并将其发送给您的第二个ViewController

-(void)buttonPressed:(NSString *)text{ 
secondViewController.title = text; 
} 

也许你将不得不实施改变标题在你的第二个ViewController如果该行不工作的方法。希望这对你有用,我理解你的问题。

+0

下面是一个协议的例子。 '@protocol myDelegate - (void)buttonPressed:(NSString *)text; @ end' [基础协议](http://mobiledevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html) – ohr 2012-07-11 22:25:33

0

没有测试过这一点,但下面应该为你工作:

navBar.topItem.title = @"title"; 

OR

[email protected]"title"; 

@ “称号” 将与字符串变量(在VC2)所设定更换在推动VC2在导航控制器堆栈之前...

欢呼声

+0

等等,那么这将如何工作?我明白你在说什么,但我会在哪里宣布所有这一切?我只需要更多的细节。 – 2012-07-11 21:43:09

+0

设置文本是我不关心的,我只需要从ViewController 2声明UINavigationBar,这样当我在ViewController 1中编写代码时,如果有意义的话,我可以使用ViewController 2中的naviBar。 – 2012-07-11 21:50:35

0

与Oscar的答案类似,但如果这是一个字符串,您希望多个视图控制器有权访问,那么您可以在您的应用程序委托中设置一个属性。

In AppDelegate 
@property (NSString *) myString; 

In View Controller setting 
myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate]; 
appDelegate.myString = @"meh"; 

In View Controller getting 
myAppDelegate *appDelegate= (myAppDelegate *)[[UIApplication sharedApplication] delegate]; 
NSString *mehStr = appDelegate.myString; 

这不是完整的代码,但你明白了。我不确定我会不会把东西放回到appdelegate,但是对于一个字符串,它应该可以正常工作。