Calling a function from a different view controller for iphone

后端 未结 3 1825
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 04:53

I have a problem where I want to call a function defined in one view controller from another controller. I\'v try what seems llke a hundred different setups and nothing seem

相关标签:
3条回答
  • 2021-01-13 05:22

    "Hi All, I have a problem where I want to call a function defined in one view controller from another controller. I'v try what seems llke a hundred different setups and nothing seems to work."

    This is because it is bad design. Controllers should not directly talk to each other.

    You should consider using delegates, notifications or some shared central entity.

    0 讨论(0)
  • 2021-01-13 05:23
    /* Ok, so based on a suggestion to use Notifications, I solved my problem.  It's
    actually so simple, it ridiculous I had so much trouble with it.   Thought I'd 
    post it just in case some other newbie hits the same type issue.
    */
    
    // in the SwitchViewController.m  I added this.  This sets it up so 
    // when the dealNotification
    // is triggered, the HideBar function I have defined in SwitchViewController 
    // gets called.
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(HideBar) name:@"dealNotification" object: nil];
    
    
    // in the GameViewController.m where I want to call the function in the other controller,
    // I added this and it send the notification to run the function
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dealNotification" object: nil];
    
    0 讨论(0)
  • 2021-01-13 05:25

    Why not just have a button send both messages directly to their respective controllers? Instances of UIButton are inherently capable of sending multiple messages to multiple targets. To configure the button, you can send the following message as many times as necessary:

    - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
    

    You can also wire the button up in Interface Builder to do the same thing. Or mix and match to your hearts content.

    0 讨论(0)
提交回复
热议问题