2013-05-12 58 views
1

我使用UITapGestureRecognizer來處理ImageviewTap操作。在主ViewController中,它工作得很好。但是,當我在我的APP中使用另一個ViewController,並複製相同的UITapRecognizer代碼時,我將一個EXC_BAD_ACCESS代碼= 1地址:0x80759d3a錯誤消息添加到我的imageview識別器中。我錯了什麼?UITapGestureRecognizer錯誤,當我添加到圖像視圖

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

最後一行我得到的崩潰。

+0

首先,您應該調用[super viewDidLoad];首先,然後添加代碼。 – danypata 2013-05-12 18:46:55

回答

0

我的問題是在我的主視圖控制器。我把這個新的viewcontroller稱爲錯誤的,併爲它指定了空指針。獲取它的財產,它的工作原理。問題不在於gesturetaprecognizer。

0

聽起來好像您的實時視圖不會保留,所以當您嘗試添加手勢時,該視圖不再存在。嘗試在您的界面中將您的實時視圖記錄爲屬性,並在您的實現中合成它。

+0

試過這個,但它不工作:(同一個錯誤,相同的行 – tomeszmh 2013-05-12 19:18:53

+0

你能否給我們你的 - (void)viewDidLoad方法和你的接口? – Franck 2013-05-12 19:25:50

+0

[鏈接] http://pastebin.com/mg1SeNf4 [鏈接] http ://pastebin.com/5DTq7Egm – tomeszmh 2013-05-12 19:30:31

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

我使用ARC,但它不起作用 – tomeszmh 2013-05-12 19:22:15

+0

如果你使用ARC,你應該聲明你的屬性是這樣的(strong,not retain):@ property(nonatomic,strong)UIImageView * live; – Franck 2013-05-12 19:35:00

+0

我設置爲屬性@屬性(非原子,強)UIImageView *生活; 並添加gesturerecognizer到_liv e,同樣的錯誤 – tomeszmh 2013-05-12 19:48:59

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