views:

278

answers:

3

Hi,

I have a small iPhone app which I've created a button with some functionality in. My question is, how can I call this button without actually pressing it?

Any help would be appreciated!

Thanks

+2  A: 

Have your button event call a function. You can also manually call the function yourself.

Example:

- (void) btnFunction {
  NSLog (@"test");
}

...

UIButton *btn1 = [UIButton buttonWithType:UIButtonRoundedRect];
// other code to set up button goes here
[btn1 addTarget:self action:@selector(btnFunction) forControlEvents:UIControlEventTouchUpInside];

You can also call the function yourself:

[self btnFunction];
Jeffrey Berthiaume
Hi, I did try this but was unsuccessful. If was had a function such as -(void)test{ ... } how would I call it elsewhere? Thanks
ing0
Sorry -- I realized I was being vague, and so typed an example. :-)
Jeffrey Berthiaume
With that edit, my answer is no longer needed. Deleting momentarily. :)
John Rudy
Thanks, exactly what I was after! Thanks for your help...
ing0
I do get a warning though telling me that my view controller may not respond to the event but it works... Hmm
ing0
is your function below the place that you called it? make sure the function is above wherever you say "[self btnFunction];"... or declare the -(void) btnFunction in the header file...
Jeffrey Berthiaume
+1  A: 

Your button shouldn't have functionality, it should just send a message to its target (or call a method, or call a function...).

You're free to send that message to that target yourself.

e.g. Your button's target outlet is connected to an IBAction on your controller. That IBAction is just a method of the form:

- (void) doSomething:(id)sender

In your own code do:

[controller doSomething:self];

It's exactly the same as having your button do it.

Terry Wilcox
Thanks for your help :)
ing0
+1  A: 

If you want to activate whatever target a button is wired to, you can call:

[button sendActionsForControlEvents:UIControlEventTouchUpInside];

(TouchUpInside is the event you'd normally wire a button action to). This way if other targets are added or changed for any button (say for debugging) you don't have to alter your code.

This method is on UIControl which UIButton inherits from, which is why you might have overlooked it at first glance...

Kendall Helmstetter Gelner