I add a UIButton
programmatically, and I want to call a method when pressing on it, I'm not sure how to design such a pattern:
where should I put event handler, or action method? in view controller or view itself.
If I put the method in view controller, how can I manipulate the SubViews
of the View in the method? should I expose all of SubViews
(UIButton
, etc.) to controller by putting them in view's header file as properties? Actually this question shall be asked in this way: How can I implement by code that SubViews
in a view are associated to an IBOutlet
properties by Interface Builder...
If you want to check If UIButton is Pressed or not, You should handle TouchDown Handler and change button's state to pressed in touchDown hadnler. You can track ToucUpInside method to Change state of button to Not-pressed again. Thank you so much. By using the addTarget syntax I solved my problem!
A control that executes your custom code in response to user interactions.
Set Button Action When the button is tapped we can make it call a function. To add an action call to our button we will need to use the addTarget() function.
Check this link for the basics of iOS view hierarchy: Getting started with iOS Views and understand the following diagram (credits: techrepublic.com):
Programmatically:
// Create your button wherever you wish (below is example button)
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0.0, 0.0, 320, 450);
[myButton setTitle:@"Yay" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(didTouchUp:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];
// This method will be called when touch up is made on the button
- (void)didTouchUp:(UIButton *)sender {
NSLog(@"Button Pressed!");
}
Explanation:
[myButton addTarget:self action:@selector(didTouchUp:) forControlEvents:UIControlEventTouchUpInside];
Using Storyboards:
Then add to the ViewController.h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *myButton;
- (IBAction)didTouchUp:(id)sender;
@end
Then add to the ViewController.m file:
- (IBAction)didTouchUp:(id)sender {
NSLog(@"Button Pressed!");
}
Lastly, create the connection between the UIButton and the IBAction:
This is the very basic flow to do such a step... you might want to expend your skills by reading the following:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With