写在前面
在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
@interface MyViewController : UIViewController
@end
4、MyViewController.m
添加MyView作为自身view
#import "MyViewController.h"
#import "MyView.h"
@interface MyViewController ()
@property (strong, nonatomic) MyView *myview;
@end