Question

I've been searching online for this answer, and every single post skips over the part of where to actually write the code for an action. I have a simple Interactive UIButton. And If i could just see a template of code that says "\write code for action here", that would be super helpful!!! ( it's for iPad IOS7 )

This is as far as I can get...

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
   action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

I think I understand that this is how to set up a potential action, but where do I write the actual code for the action itself?

Was it helpful?

Solution

I want to kind of expand more on what was answered here already, Both responses are correct but i want to explain why/how this all works.

[button addTarget:self  
   action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];

The first thing to look at; The target.

The target is the instance of a class, any class. The only requirement for this class is that it has to implement the action.

action is the method you wish to invoke when the user presses the button.

@selector(aMethod:) Basically think of this as a method signature. Because Objective-c is a dynamic language, aMethod: does not need to exist, but will crash your program if it does not.

So if we put this all together, Whenever I want to press this button:

The system will invoke the action method, on the target instance.

and for the method itself, it can look like this

- (void) aMethod:(id)sender { }

OTHER TIPS

You would put the action related code in a method, in that class, named aMethod:

- (void)aMethod:(id)sender {
    // your code for the action goes here
}

You perhaps might also want to use UIControlEventTouchUpInside for the control event.

Since you've set the target as self, the aMethod: method should be added to the same class.

- (IBAction)aMethod:(id)sender
{
  // do something here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top