【问题标题】:Two ViewControllers - First one has x buttons, second one has x labels两个 ViewControllers - 第一个有 x 个按钮,第二个有 x 个标签
【发布时间】:2012-01-08 12:36:06
【问题描述】:

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

这是我想要做的:在第一个 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 的标签 - 有人知道为什么吗?

【问题讨论】:

  • 您的“编辑”是一个单独的问题。你的意思是说:(buttonTag == 9001)。您的单个等号正在分配 buttonTag,而不是检查是否相等。所以当执行到if ((buttonTag = 9002))时,buttonTag 被分配给 9002,这是真的。所以它会改变你的标签两次。
  • 你是对的,对不起,但我不想因为它打开一个新问题。我把它改成了你的建议,但现在他只显示标签 9001 中的标签:(

标签: ios label switch-statement viewcontroller


【解决方案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-文件),您可以在推送新视图控制器之前简单地分配这些属性。这就是我们在上面的代码 sn-p 中所做的。

【讨论】:

  • 感谢您的快速回答。就像我说的,我对此很陌生,因此对 startpost 进行了编辑和编辑,因为我没有完全理解:-
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多