两个ViewControllers - 第一个有x个按钮,第二个有x个标签

时间:2012-01-08 12:36:06

标签: ios label switch-statement viewcontroller

我遇到了一个小问题(毫不奇怪,因为我刚刚开始使用xcode)。我试图用if-statemens来解决它,但它们显然是错误的方法。

以下是我要做的事情:在第一个ViewController中,我有4个按钮。如果用户按下第一个按钮,他将进入ViewController2并且标签显示“您按下了第一个按钮”。如果用户按下第二个按钮,他将进入ViewController2并且标签显示“您按下了第二个按钮”,依此类推。

我试图用Tag语句来解决它,例如: 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的标签 - 有人知道为什么吗?

1 个答案:

答案 0 :(得分: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 - 文件和@synthesize文件中.m中定义),则可以在推送新视图之前简单地分配这些属性控制器。这就是我们在上面的代码片段中所做的。