详解iOS中按钮点击事件处理方式

2020-01-18 20:07:10王振洲

写在前面

在iOS开发中,时常会用到按钮,通过按钮的点击来完成界面的跳转等功能。按钮事件的实现方式有多种,其中较为常用的是目标-动作对模式。但这种方式使得view与controller之间的耦合程度较高,不推荐使用;
另一种方式是代理方式,按钮的事件在view中绑定,controller作为view的代理实现代理方法。

目标-动作对实现方式

具体来说,假设我们有一个包含一个Button的veiw,view将Button放在头文件中,以便外部访问。然后controller将view作为自己的view,在viewcontroller中实现按钮的点击事件。文字描述起来好像不够直观,直接上代码

1、MyView.h

包含一个可被外部访问的按钮的view


@interface MyView : UIView

@property (strong, nonatomic) UIButton *myBtn;

@end

2、MyView.m


#import "MyView.h" 

@implementation MyView
//view的初始化方法
- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self)
  {  //初始化按钮
    _myBtn = [[UIButton alloc] initWithFrame:CGRectMake(140, 100, 100, 50)];
    _myBtn.backgroundColor = [UIColor redColor];
    //将按钮添加到自身
    [self addSubview:_myBtn];
  }
  return self;
}

@end

3、MyViewController.h


#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController

@end

4、MyViewController.m

添加MyView作为自身view


#import "MyViewController.h"
#import "MyView.h"

@interface MyViewController ()

@property (strong, nonatomic) MyView *myview;

@end

@implementation MyViewController

- (void)loadView
{
  MyView *myView = [[MyView alloc] initWithFrame: [[UIScreen mainScreen] bounds] ];
  self.view = myView;
  self.myview = myView;
  
  //在controller中设置按钮的目标-动作,其中目标是self,也就是控制器自身,动作是用目标提供的BtnClick:方法,
  [self.myview.myBtn addTarget:self
             action:@selector(BtnClick:)
        forControlEvents:UIControlEventTouchUpInside];
}

//MyView中的按钮的事件
- (void)BtnClick:(UIButton *)btn
{
  NSLog(@"Method in controller.");
  NSLog(@"Button clicked.");
}

5、 AppDelegate.m


 #import "AppDelegate.h"
#import "MyViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  self.window = [ [UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds ] ];
  
  MyViewController *myVC = [[MyViewController alloc] init];
  self.window.rootViewController = myVC;
  
  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
          
  return YES;
}