Search code examples
iphoneiosuiviewcontrolleribaction

On iOS, we can create an Outlet by code easily -- what about Actions?


On iOS, if we use Interface Builder, we can create Outlet and Action easily.

If we use Objective-C code instead of Interface Builder, we can create outlet quite easily too, it seems, by just

datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(200, 200, 200, 200)];
[self.view addSubview:datePicker];

and that we define an instance variable in the .h file.

UIDatePicker *datePicker;

And I think this is exactly like an Outlet?

How about for Actions -- how do we create Actions purely using Objective-C code (without using Interface Builder) for the different types of user interaction?


Solution

  • Just like this:

    - (void)someMethod {
      //...
      [button_ addTarget:self
                  action:@selector(buttonAction:)
        forControlEvents:UIControlEventTouchUpInside];
      //...
    }
    
    //...
    
    // Either |IBAction| or |void| is okay,
    //   the former one is just used to be shown in Interface Builder
    - (void)buttonAction:(id)sender {
      // your action code here
    }
    

    Note: IBOutlet & IBAction are just for IB (short for Interface Builder). You can forget it if you don't want to use Interface Builder to manage your views & actions.