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...
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.