How to add a gesture recognizer to a form drawn by uibezierpath

I draw a circle in the drawRect function in a subclass of UIView

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

I want to add a gesture recognizer to the circle to make it tappable

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

I thought of dragging the UIGestureRecognizer onto the view (in the storyboard) where the big circle will be, but the circle is much larger than the UIGestureRecognizer widget.

How can I either combine the code or assign a UIGestureRecognizer to the view area, exactly the same as the size and location of the circle?

+4
source share
2 answers

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

, . , . . .

UIView, . ( ShapesView). ShapesView . ShapesView. , , , , , .

UIBezierPath containsPoint, , .

+2

Source: https://habr.com/ru/post/1545479/


All Articles