iOS点击事件的截取(OC)

1.创建圆形ImageView按钮

 只有点击圆形内响应方法才会执行,具体实现方法如下:

//首先创建一个类继承于UIImageView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
 
        //计算直径
        _diameter = frame.size.width;
 
        //将self设置成圆形
        self.userInteractionEnabled = YES;
        self.layer.cornerRadius = _diameter / 2.0;
        self.clipsToBounds = YES;
 
        //添加单机手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(selfClick:)];
        tap.numberOfTouchesRequired = 1;
        tap.numberOfTapsRequired = 1;
       
        self.gestureRecognizers = @[tap];
    }
    return self;
}
 
//此方法如果返回NO则self不会响应点击事件
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGPoint pt;
    float radius = _diameter / 2.0f;
   
    pt.x = (point.x - radius) / radius;
    pt.y = (point.y - radius) / radius;
   
    float xsquared = pt.x * pt.x;
    float ysquared = pt.y * pt.y;
   
    if(xsquared + ysquared < 1.0) {
        return YES;
    }else {
        return NO;
    }
}
 
- (void)selfClick:(UITapGestureRecognizer *)tap
{
    //在这里可以写你要进行的单机响应事件
    CGPoint pt = [tap locationInView:self];
    NSLog(@"%@", NSStringFromCGPoint(point));
}


2.当一个视图被另一个视图遮盖时,如果想要点击被遮盖的视图可以重写父视图中的- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event 方法,具体实现方法如下:

其中hitTest:withEvent:方法中返回的View就是响应点击方法的视图

#import "CustomBtn.h"
#import "CustomImageView.h"
 
@interface CustomBtn ()
{
    CustomImageView *_cusImg;
}
@end
 
@implementation CustomBtn
 
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _cusImg = [[CustomImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
        _cusImg.backgroundColor = [UIColor yellowColor];
        [self addSubview:_cusImg];
       
        UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        coverBtn.frame = CGRectMake(100, 100, 100, 100);
        coverBtn.alpha = 0.3;
        [coverBtn addTarget:self action:@selector(subButtonClick)forControlEvents:UIControlEventTouchUpInside];
        coverBtn.backgroundColor = [UIColor greenColor];
        [self addSubview:coverBtn];
    }
    return self;
}
 
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *result = [super hitTest:point withEvent:event];
    CGPoint pt = [_cusImg convertPoint:point fromView:self];
    if ([_cusImg pointInside:pt withEvent:event]) {
        return _cusImg;
    }
    return result;
}
 
- (void)subButtonClick
{
    NSLog(@"subButtonClick");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值