Question

Might look that I didn't do my homework but I didn't find similar questions.

I am creating a UIImageView programmatically when UIView is tapped using UITapGestureRecognizer. Then I want to use/apply other UIGestureRecognizer subclasses on the created UIImageView.

What is the best solution to this?

NOTE: Current code is working and doing what I but I want avoid calling [self viewDidLoad]; from another method(look at pasteImage method).

Here is my relevant code

.h file

@property (retain, nonatomic) IBOutlet UIImageView *imageView;
@property (retain, nonatomic) IBOutlet UIImageView *character;
@property (retain, nonatomic) IBOutlet UIImage *uiImg;

.m file

@synthesize character;
@synthesize uiImg;

- (void)pasteImage:(UITapGestureRecognizer *)t

{

imageNSArray = [NSMutableArray array];
uiImg = [UIImage imageNamed:@"homer.png"];
CGPoint loc = [t locationInView:self.view];

    for (character in imageNSArray)
{
    if ([character pointInside:[character convertPoint:loc fromView:self.imageView] withEvent:nil])
    {
        [imageNSArray removeObject:character];
        [character removeFromSuperview];
        return;
    }
}

    character = [[UIImageView alloc] initWithImage:uiImg];
    character.center = loc;
    NSLog(@"self.character value %@",character);
    [imageNSArray addObject:character];
    [self viewDidLoad];
}

- (void)viewDidLoad
{
    //Tap gesture
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pasteImage:)];
    [self.previewImage addGestureRecognizer:tap];
    //Pan gesture
    character = [[UIImageView alloc]initWithImage:uiImg];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    pan.delegate = self;
    [character addGestureRecognizer:pan];
    [pan setMinimumNumberOfTouches:1];
    [pan setMaximumNumberOfTouches:1];
    character.center = self.view.center;
    [self.view addSubview:character];
    character.userInteractionEnabled = YES;
    [tap release];
    [pan release];

    [super viewDidLoad];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer 
{
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                        recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

}
Was it helpful?

Solution

Make your Tap and Pan gesture recognizers as global and declare them as you have in viewDidLoad. Then you can just enable or disable them as and when needed. This way you won't have to declare them again and again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top