2012-07-23 68 views
0

我问过一个类似于以前的问题,首先得到了很多答案,谢谢他们,但是由于项目的复杂性,我不明白答案,因此我决定再次提问以非常简单的形式。IOS制作按钮在视图控制器之间工作

我在viewcontrollerA一个按钮,我想该按钮上的标签是在viewcontrollerB.Its一个简单的一个按钮,将设置标签文本上B.

用户打开写应用

点击页面在按钮A

第二页出现,并在该标签页文本由label.text代码中设置视图 - 控制一来它调用的代码

或者我可以从B中调用A的代码,只要我做出它就不重要。我可以用buton打开另一个viewcontrorrs,所以你不需要解释它。

此外,如果周围,只要它们是简单的,我可以做他们too.Maybe我在其他地方写的代码,并从A和B.

叫它任何其他方式

请解释它一步干,因为我有关于目标C和xcode的小知识。

我问这个问题了解viewcontrollers之间的连接。在现实中,我会让该按钮在第二页显示一个随机数,但它不重要,因为如果我学会做简单的连接,我可以做其余的。

+0

你说“第二页出现”。这是一个重要的细节......这是怎么发生的?你需要的答案是不同的,取决于是否存在涉及到的代码或代码中的某些事情。 – 2012-07-23 21:46:42

回答

0

在您的操作中,您需要引用第二个视图控制器。例如

- (IBAction)buttonAClicked:(id)sender { 
    ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil]; 
    [self.navigationController pushViewController:vc2 animated:YES]; 
    vc2.someVariable = @"This is random text"; 
    [vc2.someButton setTitle:@"Some button text" forControlState:UIControlStateNormal]; 
} 

这显示了如何创建第二个视图控制器,更改两个属性,然后将其推送。

+0

我把我的第一视图controlelr命名为Ru1,第二个是Ru2,所以我想我会把这个ru1.h放在这个代码中写下我的viewcontroller的名字。 但是,什么是vc2我想你分配了一个名字它的oke,但是它破坏了我的其他连接从故事板按钮点击等为ru1 ru2 – user1546565 2012-07-23 21:49:53

+0

如果你正在尝试与故事板做到这一点。你需要命名segue,然后在 - (void)prepareForSegue:(UIStoryboardSegue *)中执行此操作。segue sender:(id)发送方法 – 2012-07-23 21:53:08

+0

在哪里应该将此代码写入第一个viewcontroller.h或第二个? – user1546565 2012-07-23 21:59:44

0

在您的第二视图控制器创建一个名为theText属性,该属性是一个NSString然后在viewDidLoad分配label.textNSString;

- (void)viewDidLoad 
{ 
    if(self.theText) 
     self.label.text = self.theText; 
} 

现在使用你的第一个视图控制器在第二个视图控制器中设置theText

如果您使用的是赛格瑞使用prepareForSegue

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"Second View Segue"]) 
    { 
     SecondViewController *theController = segue.destinationViewController; 
     theController.theText = @"Some text"; 
    } 
} 

如果您正在使用某种模式介绍:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.theText = @"Some text"; 
[self presentModalViewController:theController animated:YES]; 

,或者如果您使用的是导航控制器:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.theText = @"Some text"; 
[self.navigationController pushViewController:theController animated:YES]; 

因此,您的第一个视图控制器将设置NSString属性在第二种情况下,第二种设置UILabel等于NSString。你不能设置一个UILabel文本第二视图控制器被加载之前,所以是这样的:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.label.text = @"Some text"; 
[self.navigationController pushViewController:theController animated:YES]; 

将无法​​正常工作,因为直到视图被加载,你不能设置文本标签。

希望有所帮助。

相关问题