如何将手势识别器添加到由uibezierpath绘制的形状



我在UIView子类的drawRect函数中画了一个圆

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();  
    CGContextSetLineWidth(contextRef, 2.0);
    CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
    CGRect circlePoint = (CGRectMake(self.bounds.size.width/3, self.bounds.size.height/2, 200.0, 200.0));
    CGContextFillEllipseInRect(contextRef, circlePoint);
}

我想为圆圈添加一个手势识别器,使其可点击

UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
                                        action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];

我想把一个UIGestureRecognizer拖到视图(在故事板中)的大圆圈所在的位置,但是这个圆圈比UIGestureRecognizer小部件大得多。

我如何组合代码或分配一个UIGestureRecognizer到一个区域的视图,是完全相同的大小和圆的位置?

简短的回答是你不能。手势识别器依附于视图,而不是形状或图层。您必须为每个形状创建一个自定义视图对象。你当然可以那样做。

我建议你做的是创建一个UIView的自定义子类来管理你所有的形状。(我将称之为ShapesView)有自定义ShapesView管理自定义形状对象的数组。将手势识别器附加到ShapesView上。在响应手势的代码中,让它执行自定义命中测试,以确定点击了哪个形状,并移动形状。

UIBezierPath包含一个containsPoint方法,如果你为每个形状维护一个bezier路径,它将允许你做命中测试。

我不确定如何使用drawRect的方式你是,但我做了一些类似的使用UIBezierPath。我子类化了UIView,并让这个视图成为控制器的主视图。这是视图中的代码

- (id)initWithCoder:(NSCoder *)aDecoder {
     if (self = [super initWithCoder:aDecoder]) {
         self.shape = [UIBezierPath bezierPathWithOvalInRect:(CGRectMake(self.bounds.size.width/3, self.bounds.size.height/3, 200.0, 200.0))];
        }
     return self;
}
-(void)drawRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [self.shape fill];
}

shape是在.h文件中声明的属性。在视图控制器.m文件中,我添加了手势识别器,并检查触摸是否在形状内

@interface ViewController ()
@property (strong,nonatomic) RDView *mainView;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.mainView = (RDView *)self.view;
    UITapGestureRecognizer *singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:singleFingerTap];
}
-(void)handleSingleTap:(UITapGestureRecognizer *) tapper {
    if ([self.mainView.shape containsPoint:[tapper locationInView:self.mainView]]) {
        NSLog(@"tapped");
    }
}

最新更新