#import <UIKit/UIKit.h> @interface LPButton : UIView @property (nonatomic,strong) id target; @property (nonatomic,assign) SEL action; - (void)addTarget:(id)target action:(SEL)action; @end
//
// LPButton.m
// loopdiner
//
// Created by yl on 15/12/8.
// Copyright © 2015年 yl. All rights reserved.
//
#import "LPButton.h"
@implementation LPButton
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self createMyView];
}
return self;
}
- (void)createMyView {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[self addGestureRecognizer:tap];
}
/*
//或者不添加tap事件,直接调用这个事件
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touche = [touches anyObject];
CGPoint point = [touche locationInView:self];
if (CGRectContainsPoint(self.bounds, point))
{
[self.target performSelector:self.action withObject:self];
}
}
*/
- (void)tapAction {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self.target performSelector:self.action withObject:self];
#pragma clang diagnostic pop
}
- (void)addTarget:(id)target action:(SEL)action {
self.target = target;
self.action = action;
}
@end
这里只是一种方法,还可以通过代理等方法实现。
原文:http://www.cnblogs.com/siasyl/p/5053249.html