事件拦截

来源:互联网 发布:cf永久刷枪软件 编辑:程序博客网 时间:2024/05/17 23:47
#import "ContentView.h"@implementation ContentView- (instancetype)initWithFrame:(CGRect)frame{    if (self = [super initWithFrame:frame])    {        UIButton *b1 = [UIButton buttonWithType: UIButtonTypeCustom];        b1.backgroundColor = [UIColor redColor];        b1.frame = CGRectMake(20, 40, 300, 300);        [b1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];        b1.tag = 1;        [self addSubview:b1];                UIButton *b2 = [UIButton buttonWithType: UIButtonTypeCustom];        b2.backgroundColor = [UIColor yellowColor];        b2.frame = CGRectMake(20, 40, 260, 200);        [b2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];        b2.tag = 2;        [b1 addSubview:b2];                UIButton *b3 = [UIButton buttonWithType:UIButtonTypeCustom];        b3.frame = CGRectMake(40, 400, 200, 200);        [b3 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];        b3.tag = 3;        b3.backgroundColor = [UIColor purpleColor];        b3.layer.cornerRadius = b3.frame.size.width/2;        [self addSubview:b3];    }        return self;}- (void)buttonClick:(UIButton *)btn{    NSLog(@"---%ld",btn.tag);}//触摸开始//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event//{//    NSLog(@"contentView");//}//触摸事件交给哪个视图处理- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{    UIButton *btn1 = (UIButton *)[self viewWithTag:1];    UIButton *btn3 = (UIButton *)[self viewWithTag:3];        //按钮3的中心    CGPoint center = btn3.center;        //触摸点到btn3的中心的距离    CGFloat distance = sqrtf((center.x - point.x)*(center.x - point.x) + (center.y - point.y)*(center.y - point.y));        //CGRectContainsPoint(frame, point)表示point点是否在frame范围内。    if (CGRectContainsPoint(btn1.frame, point))    {        //如果点击的坐标在按钮的范围内,事件交给btn1处理        return btn1;    }    //在圆形范围内    else if (distance <= btn3.frame.size.width/2)    {        return btn3;    }        return self;}/*// Only override drawRect: if you perform custom drawing.// An empty implementation adversely affects performance during animation.- (void)drawRect:(CGRect)rect {    // Drawing code}

#import "ViewController.h"#import "ContentView.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.                ContentView *contentView = [[ContentView alloc] initWithFrame:self.view.bounds];    [self.view addSubview:contentView];            }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

1 0
原创粉丝点击