开发者

Parent VeiwControllers of ViewControllers

开发者 https://www.devze.com 2023-01-15 19:50 出处:网络
My main view PlayGameViewController has a subview (actually 2 of them) called CardViewController. CardViewController creates some buttons programmatically

My main view PlayGameViewController has a subview (actually 2 of them) called CardViewController.

CardViewController creates some buttons programmatically

  -(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 add开发者_开发问答Target:self action:@selector(statTapped:) 
                forControlEvents:UIControlEventTouchUpInside];
        sv.overlayButton.tag = 10 + i;
        [self.frontView addSubview:sv];
        ypos += 26;
    }
  }

It sets a callback function statTapped. This works ok and the function does get called. But... All the game logic is in PlayGameViewController so I need to handle the function there. I tried deleting the function from CardViewController and implementing it instead in the PlayGameViewController but the call wasn't passed down to the parent class.

Is there away to achieve this or am I talking and thinking crazy?


I think you have a couple of options:

  1. Create a delegate to process your statTapped: method. You can learn more about delegates and how to create one here: How do I create delegates in Objective-C?
  2. Use NSNotification and add a listener in PlayGameViewController that will call the statTapped: method (also defined in PlayGameViewController. Then in CardViewController have your selector action call a method that posts a notification. PlayGameViewController will receive that notification and then run the specified tasks.

Here is an example of using NSNotification:

In your PlayGameViewController's init method, write:

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

In CardViewController, you'll want to set a selector to your button action as you do now, but instead of statTapped: you'll want a different method which contains this code:

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

By doing so your PlayGameController will own the statTapped method.

Don't forget to remove the observer in your viewDidUnload method:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"statTapped" object:nil];
0

精彩评论

暂无评论...
验证码 换一张
取 消