最近用 ReactiveCocoa ,相见恨晚。不过遗憾的是没有提供一个添加 Gesture Recognizer 的接口。看了一下 RAC 提供的其他 Category 的实现,感觉实现起来也不难,于是就撸了一个。
没啥技术含量,但用起来真的相当方便。
//添加点击的处理事件
[[self.view rac_signalForGestureRecognizer:[UITapGestureRecognizer class]] subscribeNext:^(UITapGestureRecognizer * x) {
NSLog(@"view tapped at %f,%f", [x locationInView:x.view].x,[x locationInView:x.view].y);
}];
//添加仅针对 View 中特定区域的拖动检测
[[[self.view rac_signalForGestureRecognizer:[UIPanGestureRecognizer class]] filter:^BOOL(id value) {
UIPanGestureRecognizer* pgr = (UIPanGestureRecognizer*)value;
CGRect rect = CGRectMake(100, 100, 200, 200);
return CGRectContainsPoint(rect, [pgr locationInView:pgr.view]);
}] subscribeNext:^(id x) {
NSLog(@"panned in given rect");
}];
//缩放事件
[[self.view rac_signalForGestureRecognizer:[UIPinchGestureRecognizer class]] subscribeNext:^(id x) {
NSLog(@"view pinched");
}];
//可拖拽 view 的一个非常简单的实现方式
UIView* t = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
t.backgroundColor = [UIColor yellowColor];
[self.view addSubview:t];
RAC(t,center) = [[t rac_signalForGestureRecognizer:[UIPanGestureRecognizer class]] map:^id(UIPanGestureRecognizer* value) {
CGPoint p = [value translationInView:self.view];
[value setTranslation:CGPointZero inView:self.view];
return [NSValue valueWithCGPoint:CGPointMake(t.center.x + p.x, t.center.y + p.y)];
}];