ViewControllers的父视图控制器

时间:2010-09-13 20:16:43

标签: iphone objective-c

我的主视图PlayGameViewController有一个名为CardViewController的子视图(实际上有2个)。

CardViewController以编程方式创建一些按钮

  -(void) initialiseButtons 
  {
    NSLog(@"initialiseButtons  %d",totalButtons);
    int ypos = playerImage.frame.origin.y + playerImage.frame.size.height + 42;
    for(int i=0; i<totalButtons; i++) 
    {       
        StatView *sv = [[StatView alloc] initWithYPos:ypos];
        sv.tag = 100 + i;
        [sv.overlayButton addTarget:self action:@selector(statTapped:) 
                forControlEvents:UIControlEventTouchUpInside];
        sv.overlayButton.tag = 10 + i;
        [self.frontView addSubview:sv];
        ypos += 26;
    }
  }

它设置一个回调函数statTapped。这工作正常,函数确实被调用。 但是......所有游戏逻辑都在PlayGameViewController中,所以我需要处理那里的功能。我尝试从CardViewController中删除该函数并在PlayGameViewController中实现它,但调用没有传递给父类。

有没有实现这一点,还是我在说话和思考疯狂?

1 个答案:

答案 0 :(得分:0)

我认为你有几个选择:

  1. 创建委托以处理您的statTapped:方法。您可以在此处详细了解代表以及如何创建代表:How do I create delegates in Objective-C?
  2. 使用NSNotification并在PlayGameViewController中添加一个将调用statTapped:方法的监听器(也在PlayGameViewController中定义。然后在CardViewController中执行您的选择器操作调用发布通知的方法。PlayGameViewController将收到该通知,然后运行指定的任务。
  3. 以下是使用NSNotification

    的示例

    PlayGameViewController的init方法中,写一下:

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(statTapped:) 
                                                 name:@"statTapped"
                                               object:nil];
    

    CardViewController中,您需要像现在一样为按钮操作设置选择器,但不是statTapped:,而是需要包含此代码的其他方法:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"statTapped" 
                                                        object:self];
    

    通过这样做,PlayGameController将拥有statTapped方法。

    不要忘记用viewDidUnload方法删除观察者:

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"statTapped" object:nil];
    
相关问题