检测点击UIImageView IOS

时间:2014-03-25 09:01:45

标签: ios imageview uitapgesturerecognizer

我做错了吗?我无法检测UIImageview上的点按。 UIImageView *myImage是在故事板中创建的。代码文件位于:https://drive.google.com/folderview?id=0B2jWw-2wZC52NDBFZ2lXUTUzQXM&usp=sharing

档案:ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIImageView *myImage;

@end

档案:ViewController.m

#import "ViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIGestureRecognizer *tapGestureRecognizer = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tappedImage:)];
    [self.myImage addGestureRecognizer:tapGestureRecognizer];
    self.myImage.userInteractionEnabled = YES; // default is no for UIImageView

}

- (void)tappedImage:(UIGestureRecognizer *)gestureRecognizer {
    //UIImageView *myImage = (UIImageView *)gestureRecognizer.view;
    // do stuff;
    NSLog(@"it works");
}


@end

5 个答案:

答案 0 :(得分:22)

我认为你应该使用UITapGestureRecognizer类作为:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
preArrowImage.userInteractionEnabled = YES;
[preArrowImage addGestureRecognizer:singleTap];

-(void)tapDetected{
NSLog(@"single Tap on imageview");

}

答案 1 :(得分:8)

您只需将.h文件更改为

即可
 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController<UIGestureRecognizerDelegate>

@property (strong, nonatomic) IBOutlet UIImageView *myImage;

@end

然后是.m文件

 #import "ViewController.h"
 @interface ViewController ()

 @end

 @implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

UIGestureRecognizer *tapGestureRecognizer = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tappedImage:)];
tapgestureRecognizer.delegate = self;
[self.myImage addGestureRecognizer:tapGestureRecognizer];
self.myImage.userInteractionEnabled = YES; // default is no for UIImageView

}

 - (void)tappedImage:(UIGestureRecognizer *)gestureRecognizer {
//UIImageView *myImage = (UIImageView *)gestureRecognizer.view;
// do stuff;
NSLog(@"it works");
 }


@end

我将tapgestureRecognizer连接到委托。您只需尝试此代码

答案 2 :(得分:2)

即使您是通过代码启用它,尝试转到故事板检查图像视图上的“启用用户交互”,您的代码似乎没问题,请尝试并让我知道。

加上,只是想一想,在分配tapgesture之前尝试在imageview上启用交互:)

答案 3 :(得分:2)

 UIGestureRecognizer *sliderTapview1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedImage:)];
    [img addGestureRecognizer:sliderTapview1];

   img.userInteractionEnabled = YES;

只需替换它。

答案 4 :(得分:0)

看起来每件事都很好,尝试这样做 [myImage userInteractionEnabled:YES]并删除&#34;自动布局&#34;和&#34;启用用户互动&#34;在图像视图的界面构建器中。