UIImageView for pushing a new ViewController

2019-09-09 09:03发布

问题:

In my app for a specific reason i want a UIImageView touchable so that when user taps it pushes to a new view controller. I know to do the same with UIButton. But i want a UIImageView to do this now. How will i do it? Here's my code for UIImageView

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 50, 50)];
[imageView setImage:[UIImage imageNamed:@"myImage.png"]];
 imageView.userInteractionEnabled = YES;
[self.view addSubview:imageView];
[imageView release];

回答1:

As @Kory Sharp said you can use the UITapGestureRecognizer

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[tap setNumberOfTapsRequired:1];
[yourImageView addGestureRecognizer: tap];

Handle the method

-(void) handleTap:(UITapGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        //push your view controller
    }
}


回答2:

While it would be easier to make this a UIbutton (as you me mentioned), you can implement a UITapGestureRecognizer for the UIImageView. You'll also need to enable user interaction on the view with the userInteractionEnabled property.



回答3:

I am using a single tap gesture recognizer here

{
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 50, 50)];
     [imageView setImage:[UIImage imageNamed:@"myImage.png"]];
     UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
     [tapGesture setNumberOfTapsRequired:1];
     [tapGesture setNumberOfTouchesRequired:1];

     [imageView setGestureRecognizers:[NSArray arrayWithObject:tapGesture]];
     [tapGesture release];
     imageView.userInteractionEnabled = YES;
     [self.view addSubview:imageView];
     [imageView release];
 }

-(void)imageTapped:(id)sender
{
  // Do STUFF HERE
}


回答4:

Here is the complete code as Mat discussed about:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 50, 50)];
    [imageView setImage:[UIImage imageNamed:@"tap.png"]];
     [self.view addSubview:imageView];
    imageView.userInteractionEnabled = YES;


    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tap setNumberOfTapsRequired:1];
    [tap setNumberOfTouchesRequired:1];
    [imageView addGestureRecognizer: tap];
    [tap release];
    [imageView release];
}

-(void) handleTap:(UITapGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {


       MyTestViewController* viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"TestTable"];
        [self.navigationController pushViewController:viewController animated: YES];

    }
}