UITapGestureRecognizer错误,当我添加到一个图像视图



我使用UITapGestureRecognizer来处理一个ImageviewTap动作。在主视图控制器中它工作得很好。但是,当我在我的应用程序中使用另一个ViewController,并复制相同的UITapRecognizer代码时,我得到EXC_BAD_ACCESS代码=1地址:0x80759d3a错误消息到我将识别器添加到我的imageview时。我做错了什么?

My ImageView: It works

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];

和最后一行我得到崩溃

听起来你的实时视图没有保留,所以当你尝试添加手势时,视图不再存在。试着把你的实时视图作为一个属性记录在你的接口中,并在你的实现中合成它。

我不确定这是否会导致你的代码崩溃,但你应该调用

[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];

我测试了下面的代码,它可以工作。接口:

#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

我的问题是在我的主视图控制器。我调用新的视图控制器错误,并得到空指针为它。把它用在财产上,它就起作用了。问题不在于手势识别器

相关内容

  • 没有找到相关文章

最新更新