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");
}