2012-01-08 65 views
0

我遇到了一个小问题(毫不奇怪,因为我刚开始使用xcode)。我试图用if语句解决它,但他们显然是错误的路要走。两个ViewControllers - 第一个有x个按钮,第二个有x个标签

这是我想要做的:在第一个ViewController我有例如4个按钮。如果用户按下第一个按钮,他将进入ViewController2并且标签显示“您按下了第一个按钮”。如果用户按下第二个按钮,他将进入ViewController2并且标签显示“您按下了第二个按钮”等等。

我试着用标签声明来解决这个问题,比如: FirstViewController.m

- (IBAction)switch:(id)sender; 

{ 
UIButton *buttonPressed = (UIButton *)sender; 
SecondViewController *second =[[SecondViewController alloc] initWithNibName:nil bundle:nil]; 
[self presentModalViewController:second animated:YES]; 
second.buttonTag = buttonPressed.tag; 
[self.navigationController pushViewController:second animated:YES]; 
(button.tag = 9001); 


- (IBAction)switch2:(id)sender2; 

{ 
UIButton *buttonPressed = (UIButton *)sender2; 
SecondViewController *third =[[SecondViewController alloc] initWithNibName:nil bundle:nil]; 
[self presentModalViewController:third animated:YES]; 
second.buttonTag = buttonPressed.tag; 
[self.navigationController pushViewController:third animated:YES]; 
(button2.tag = 9002); 

在这里,我在SecondViewController.m

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

if (buttonTag == 9001) { 
    self.label1.text = [[NSString alloc] initWithFormat:@"Radnomtext"]; 
    self.label2.text = [[NSString alloc] initWithFormat:@"Randomtext"]; 
    self.label3.text = [[NSString alloc] initWithFormat:@"Randomtext?"]; 

if (buttonTag == 9002) { 
    self.label1.text = [[NSString alloc] initWithFormat:@"Radnomtext2"]; 
    self.label2.text = [[NSString alloc] initWithFormat:@"Randomtext2"]; 
    self.label3.text = [[NSString alloc] initWithFormat:@"Randomtext2?"]; 

他总是给我的标签ButtonTag 9001 - 有人知道为什么吗?

+0

你的'编辑'是一个单独的问题。你的意思是说:'(buttonTag == 9001)'。您的单个等号是分配buttonTag,而不是检查是否相等。所以当执行到'if((buttonTag = 9002))'buttonTag被分配到9002,这是真的。所以它会更改标签两次。 – NJones 2012-01-08 15:04:42

+0

你说得对,对不起,但我不想因为它而开一个新的问题。我改变了你的建议,但现在他只显示标签9001:( – Blade 2012-01-08 15:11:17

回答

1

这是一个方便的小技巧给你:标签

每个UIView可以有一个属性tag。它是一个简单的整数,您可以在代码(button.tag = 456;)或Interface Builder中分配它。在你switch方法,只需使用:

-(IBAction)switch:(id)sender { 
    UIButton *buttonPressed = (UIButton *)sender; 
    // create the second view controller, e.g. 
    SecondViewController *secondViewController = [[SecondViewController alloc] init]; 
    // it should have an NSInteger @property e.g. "buttonTag" 
    secondViewController.buttonTag = buttonPressed.tag 
    [self.navigationController 
     pushViewController:secondViewController animated:YES]; 
    // if not using ACT: [secondViewController release]; 
} 

所以只是为了确保:你的说法

这是一个没有去从一个传递属性或值到另一个视图控制器

是完全错误的。如果新的视图控制器具有@property(您在.h文件中定义的文件和在.m文件中定义的@synthesize),则可以在推送新视图控制器之前简单地分配这些属性。这就是我们在上面的代码片段中所做的。

+0

谢谢你的快速回答。就像我说我对这个相当新,因此作出和编辑startpost,因为我没有完全理解: - < – Blade 2012-01-08 13:39:37

相关问题