iosobjective-cxcodeuicontroltarget-action

How can I specify a target for my action to point to?


I'm learning objective-c for iOS and have a question about creating my first target-action mechanism. I've got it to work, but currently I just set the target: portion of the addTarget:action:changeForControlEvents: method to nil, meaning it will search around my app for the target instead of drilling down on ViewController.m, where the method I want to send a message is located.

How can I tell the addTarget:action:changeForControlEvents: method which class to search first?

Here is a simple version of my current code:

The view:

// View.m
#import View.h

@implementation

- (void)sendAction
{
     UIControl *button = [[UIControl alloc] init];
     [button addTarget:nil  // How do I make this look for ViewController.m?
                action:@selector(changeButtonColor) 
changeforControlEvents:UIControlEventTouchUpInside];
}
@end

...and the View Controller:

// ViewController.m
#import ViewController.h

@implementation

- (void)target
{
     NSLog(@"Action received!");
}
@end

Thanks for the help!


Solution

  • You cannot simply called UIViewController if it doesn't load or allocate in the memory. To achieve this you need to alloc that class.

    one way to do using singleton

    [button addTarget:[ViewController sharedManager] action:@selector(target) 
    forControlEvents:UIControlEventTouchUpInside];
    

    or using NSNotificationCenter, assuming that the class is already running (stack in previous navigation / another tabs).

    // View.m
    #import View.h
    @implementation
    
    - (void)sendAction
    {
         UIControl *button = [[UIControl alloc] init];
         [button addTarget:self 
                    action:@selector(controlAction) 
    changeforControlEvents:UIControlEventTouchUpInside];
    }
    
    -(void)controlAction
    {
     [[NSNotificationCenter defaultCenter] 
            postNotificationName:@"changeButtonColor" 
            object:self];
    }
    @end
    

    and for target UIViewController

    // ViewController.m
    #import ViewController.h
    
    @implementation
    -(void) viewDidLoad
    {
       [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(receiveNotification:) 
            name:@"changeButtonColor"
            object:nil];
    
    - (void)receiveNotification:(NSNotification *) notification
    
    {
         NSLog(@"Action received!");
    }
    @end