2

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?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

3

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.

Kjuly
  • 34,476
  • 22
  • 104
  • 118
  • how come your button variable is `button_` (with underscore)? I also see some code such as ViewController having `_view` as an instance variable but the underscore is in front – nonopolarity May 25 '12 at 03:24
  • 2
    He chose to define his matching iVars with an underscore. It's just traditional, in fact, `@Synthesize button =hrighaohfunaksifh___` would work just as well. – CodaFi May 25 '12 at 03:25
  • 1
    @動靜能量 CodaFi is right. You can refer it [HERE](http://stackoverflow.com/questions/8832091/ivar-vs-ivar-for-variable-naming) if you're interested in. :) – Kjuly May 25 '12 at 03:29
  • so the convention is, if it is iOS framework code, use `_foo` for ivar names, and if it is our own app's code, use `foo_` for ivar names... and that's to distinguish between ivars and local vars... sort of like Ruby's `@foo` for ivars. – nonopolarity May 25 '12 at 03:43
  • @動靜能量 use `_foo` is fine, just be careful on naming. :) – Kjuly May 25 '12 at 03:59
1

Using the IBAction macro:

 // in .h
 -(IBAction) myAction:(id) sender;
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • I'm sure he means `addTarget:action:forControlEvents:` from the `UIControl` class, although his question really is quite ambiguous. – JustSid May 25 '12 at 02:56
  • I mean, we can have the event handler and change the property of the control using Interface Builder's outlet and action. What if we do it purely by Objective-C (without Interface Builder)? – nonopolarity May 25 '12 at 02:58