1

我使用 UITapGestureRecognizer 来处理 ImageviewTap 动作。在主 ViewController 中效果很好。但是,当我在我的 APP 中使用另一个 ViewController 并复制相同的 UITapRecognizer 代码时,当我将识别器添加到我的图像视图时,我会收到一条 EXC_BAD_ACCESS 代码 = 1 地址:0x80759d3a 错误消息。我错了什么?

我的 ImageView:它有效

UIImageView *live;
live = [[UIImageView alloc]initWithFrame:CGRectMake(92, 230, 136, 100)];
live.image = [UIImage imageNamed:@"online.png"];
[live addSubview:onlineLabel2];
[live setUserInteractionEnabled:YES];
[self.view addSubview:live];
[super viewDidLoad];

和我的手势识别器:

UITapGestureRecognizer *singleTaP3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onlineTap:)];
singleTaP3.numberOfTapsRequired = 1;
singleTaP3.numberOfTouchesRequired = 1;    
[live addGestureRecognizer:singleTaP3];

最后一行我崩溃了。

4

4 回答 4

0

听起来您的实时视图没有保留,因此当您尝试添加手势时,视图不再存在。尝试将您的实时视图记录为界面中的属性,并在您的实现中合成它。

于 2013-05-12T18:49:24.763 回答
0

我不确定这是否会导致您的代码崩溃,但您应该致电

[super viewDidLoad]; 

在代码的开头。(如果您使用的是 ARC,那么这看起来还不错。)

[super viewDidLoad]; 
UIImageView *live;
live = [[UIImageView alloc]initWithFrame:CGRectMake(92, 230, 136, 100)];
live.image = [UIImage imageNamed:@"online.png"];
[live addSubview:onlineLabel2];
[live setUserInteractionEnabled:YES];
[self.view addSubview:live];
于 2013-05-12T19:02:09.573 回答
0

我测试了以下内容,它可以工作。界面:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) UIView *v;

- (void)tapAction;

@end

和实施:

#import "ViewController.h"

@implementation ViewController

@synthesize v=_v;

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

    _v = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    [_v setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:_v];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;

    [_v addGestureRecognizer:tap];
}

- (void)tapAction
{
    NSLog(@"tap tap");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
于 2013-05-12T21:14:11.483 回答
0

我的问题出在我的主视图控制器中。我错误地调用了新的视图控制器,并为它获取了空指针。把它放在财产中,它就起作用了。问题不在于gesturetaprecognizer。

于 2013-05-13T10:28:08.553 回答