为什么我的触摸事件不起作用?

时间:2013-04-04 03:10:38

标签: objective-c

我已经在我的控制器中声明了一个void touchesbegan方法,但它不起作用!我不知道为什么。我有一个图像视图,我打算点击它移动到下一个控制器。所以我设置了触摸开始的方法。我已经链接了xib文件中的图像视图,但是当我单击图像时。什么都没发生。请帮忙,谢谢。

ViewController.h

#import <UIKit/UIKit.h>

@interface imageViewViewController : UIViewController
{
    IBOutlet UIImageView *testing;
}
@property(nonatomic, retain) IBOutlet UIImageView *testing;

@end

ViewController.m

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    UITouch *touch = [touches anyObject];

    if(touch.view == testing)
    {
        TestViewController *testviewcontroller = [[TestViewController alloc]initWithNibName:nil bundle:nil];

        [self.navigationController pushViewController:testviewcontroller animated:YES];
    }
}

@end

P.S。

这里我尝试了另一种使用轻击手势的方法。 testing是我的图像视图的名称。你可以看到我在imagedidtapped方法中注释了ns日志。它的工作直到那一点。然而,当我试图将它导航到另一个页面时,它失败了。

- (void)viewDidLoad
{


    UITapGestureRecognizer *tapRecognizer;
    [testing setTag:0]; 
    [testing setUserInteractionEnabled:TRUE];
    tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidTapped:)] autorelease];
    tapRecognizer.numberOfTapsRequired = 1;
    [testing addGestureRecognizer:tapRecognizer];
    [self.view addSubview:testing];
    [testing release];





    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}



- (void)imageViewDidTapped:(UIGestureRecognizer *)aGesture {
    UITapGestureRecognizer *tapGesture = (UITapGestureRecognizer *)aGesture;

   UIImageView *tappedImageView = (UIImageView *)[tapGesture view];

    switch (tappedImageView.tag) {
        case 0:
            //NSLog(@"UIImageView 1 was tapped");
            [self navigate];

            break;
        case 1:
            NSLog(@"UIImageView 2 was tapped");
            break;
        default:
            break;
    }
}



-(void)navigate
{
    TestViewController *testviewcontroller = [[TestViewController alloc]initWithNibName:nil bundle:nil];

    [self.navigationController pushViewController:testviewcontroller animated:YES];
}

1 个答案:

答案 0 :(得分:1)

问题是,对于UIImageView,默认情况下userInteractionEnabled为NO,因此您不会接触任何内容。将其设置为YES。

touchesBegan的消息处理也非常复杂。如果您将UITapGestureRecognizer附加到图像视图,您会更高兴。

编辑:现在你说你的触摸处理正在工作,但导航没有发生。因此,让我们专注于您的代码的这一部分:

-(void)navigate
{
    TestViewController *testviewcontroller = [[TestViewController alloc]initWithNibName:nil bundle:nil];

    [self.navigationController pushViewController:testviewcontroller animated:YES];
}

将记录放在那里以确保调用navigate!如果没有被调用,你需要弄清楚为什么你的其他代码没有运行并调用它。如果 被调用,那么问题可能是self.navigationController为零,即您不在导航界面内开始。