在我的应用程序中,由于特定原因,我希望UIImageView可触摸,以便在用户点击时推送到新的视图控制器。我知道要对UIButton做同样的事情。但我现在想要一个UIImageView来做这件事。我该怎么办? 这是我的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];
答案 0 :(得分:1)
虽然将它设置为UI按钮(如我所述)会更容易,但您可以为UIImageView实现UITapGestureRecognizer。您还需要使用userInteractionEnabled属性在视图上启用用户交互。
答案 1 :(得分:1)
正如@Kory Sharp所说,你可以使用UITapGestureRecognizer
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[tap setNumberOfTapsRequired:1];
[yourImageView addGestureRecognizer: tap];
处理方法
-(void) handleTap:(UITapGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateEnded) {
//push your view controller
}
}
答案 2 :(得分:0)
我在这里使用单击手势识别器
{
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
}
答案 3 :(得分:0)
以下是Mat讨论的完整代码:
- (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];
}
}