objective c - Connect a UITapGestureRecognizer to a UIView -


i'm trying connect gesture uiview can tap on object, not working. doing wrong?

shape.h

#import <uikit/uikit.h>  @interface shape : uiview;   - (id) initwithx: (int)xval andy: (int)yval;  @end 

shape.m

#import "shape.h"  @implementation shape   - (id) initwithx:(int )xval andy:(int)yval {     self = [super init];         uiview *shape = [[uiview alloc] initwithframe:cgrectmake(xval, yval, 10, 10)];     shape.backgroundcolor = [uicolor redcolor];     shape.userinteractionenabled = yes;          [self addsubview:shape];     return self; }  @end 

modified code: following code in main viewcontroller. have removed uitapgesturerecognizer shape class. code works if make following change, 'box' responds tap gesture, not 'shape': [shape addgesturerecognizer:tap]; [box addgesturerecognizer:tap];

- (void)handlertap:(uitapgesturerecognizer *)recognizer {     //cgpoint location = [recognizer locationinview:[recognizer.view superview]];     nslog(@"success"); } -(void)drawshapes{     nslog(@"draw");     if(!box){         box = [[uiview alloc] initwithframe:cgrectmake(0, 0, screenwidth, screenheight-100)];         box.backgroundcolor = [uicolor colorwithred: 0.8 green: 0.8 blue: 0.0 alpha:0.2];         [self.view addsubview:box];     }     (int = 0; i<5; i++) {         int x = arc4random() % screenwidth;         int y = arc4random() % screenheight;         shape * shape =[[shape alloc] initwithx:x andy:y ];         [box addsubview:shape];         uitapgesturerecognizer *tap = [[uitapgesturerecognizer alloc] init];         [tap setnumberoftapsrequired:1];         [tap addtarget:self action:@selector(handlertap:)];         [box addgesturerecognizer:tap];          } } 

solution: have learned self = [super init]; needs changed include cgrect defines boundaries of view *shape placed into. self = [super initwithframe:cgrectmake(xval, yval, 10, 10)];

also, *shape needs placed @ 0,0 ensure correct placement within parent. uiview *shape = [[uiview alloc] initwithframe:cgrectmake(0, 0, 10, 10)];

#import "shape.h"  @implementation shape   - (id) initwithx:(int )xval andy:(int)yval {     self = [super initwithframe:cgrectmake(xval, yval, 10, 10)];         uiview *shape = [[uiview alloc] initwithframe:cgrectmake(0, 0, 10, 10)];     shape.backgroundcolor = [uicolor redcolor];     shape.userinteractionenabled = yes;          [self addsubview:shape];     return self; } @end 

you should set target of gesture recognizer self, not view, because implemented handlertap: method in shape class.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -