您的位置:首页 > 产品设计 > UI/UE

UIView局部点击

2014-03-03 19:11 302 查看
今天上班遇到一种情况,需要局部响应点击事件,比如在一个UIImageView中设置一个小圆圈图片,要求点击圆圈里面不响应点击,点击小圆圈外面的部分响应点击。
可以通过重写hitTest:withEvent: 和 pointInside: withEvent:方法来做到。

看一下hitTest:withEvent
*touch事件发生,创建UIEvent对象

*按照Application的view层次结构,逐层调用每个view的hitTest:withEvent:方法,并传入该event对象,view根据hitTest:withEvent:方法和来决定touch点是否包含在自己的bounds中;

*如果view的bounds包含了touch点,该view会遍历自己的subview,并调用每个subview的pointInside:withEvent:方法来进一步决定touch事件是发生在自己本身,还是自己的subview上。

*重复第二,三步,并筛选出最终接受touch事件的view对象

//继承 建子类 重写上述方法

@interface CustomImageView : UIImageView

@property (strong, nonatomic) UIBezierPath *bezierPath;

@end

@implementation CustomImageView

- (id)init

{

self = [super init];

if (self) {

}

return self;

}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

UIView *result = [super hitTest:point withEvent:event];

return [self pointInside:point withEvent:event] ? self : result;

}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event

{

return CGPathContainsPoint(self.bezierPath.CGPath, NULL, point, YES) ? YES : NO;

}

@end


View Code
//使用部分的代码
//中间的图片

CustomImageView *imageView = [[CustomImageView alloc] initWithFrame:CGRectMake(0,0, imageWidth02, imageHeight02)];

imageView.backgroundColor = [UIColor clearColor];
imageView.userInteractionEnabled = YES;

imageView.bezierPath = [UIBezierPath bezierPathWithOvalInRect:imageView.bounds];

imageView.image = [UIImage imageNamed:kCenterImg];

[self.view addSubview:imageView];


//这样就达到了点击局部响应事件的效果。关于userInteractionEnabled这个属性设置为NO的时候,表示这个view从事件队列移除出去。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: