简体   繁体   中英

How to create event for UIButton in ViewController?

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:

  1. where should I put event handler, or action method? in view controller or view itself.

  2. 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):

致谢:http://www.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];
  • myButton - your button view
  • addTarget - the target in which the method exist in
  • action - the selector you want to call
  • forControlEvents - control event the user will do to trigger this action

Using Storyboards:

在此输入图像描述

  • (A) Make sure the storyboard is corresponding to the correct class
  • (B) Drag UIButton from the object library into the storyboard

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:

在此输入图像描述

  • (A) Right click on the button view
  • (B) Drag touch up action to the button view on the storyboard
  • (C) Press on didTouchUp:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM