1

我已經使用了UITapGestureRecognizer噸次,但在這種情況下,當tap發生時我得到了EXC_BAD_ACCESS。我認爲這與我將其添加到警報類型疊加視圖的事實有關。而且由於某些原因,即使在屏幕上,重疊視圖也不會被保留。UITapGestureRecognizer EXC_BAD_ACCESS在自包含的UIView子類中

我創建這樣的觀點:

HelperView *testHelper = [HelperView helperWithBodyText:@"test text"]; 
[testHelper presentAtPoint:screenCenter]; 

在HelperView.m的簡便方法是這樣的:

+ (id)helperWithBodyText:(NSString*)text 
{ 
    return [[self alloc] initWithFrame:CGRectZero bodyText:text]; 
} 

而其餘代碼如下所示:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     self.container = [[AGWindowView alloc] initAndAddToKeyWindow]; 
     self.container.supportedInterfaceOrientations = UIInterfaceOrientationMaskLandscapeRight; 

     self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
     self.overlay.backgroundColor = [UIColor redColor]; 
     self.overlay.alpha = 0.6; 
     [self.container addSubviewAndFillBounds:self.overlay]; //this fills the screen with a transparent red color, for testing 

     UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMe:)]; 
     [self.overlay addGestureRecognizer:tap]; //I want to dismiss the whole view if the overlay is tapped 

     self.content = [[UIView alloc] initWithFrame:CGRectZero]; 
    } 
    return self; 
} 

- (id)initWithFrame:(CGRect)frame bodyText:(NSString*)bodyText 
{ 
    self = [self initWithFrame:frame]; 
    if (self) { 

     //TEST frame 
     self.content.frame = CGRectMake(0, 0, 217, 134); 

     // Initialization code 
     UIImage *bgImage = [[UIImage imageNamed:@"helper-bg"] 
           resizableImageWithCapInsets:UIEdgeInsetsMake(30, 28, 20, 20)]; 
     UIImageView *bgImgView = [[UIImageView alloc] initWithImage:bgImage]; 
     bgImgView.bounds = self.content.frame; 
     [self.content addSubview:bgImgView]; 

} 
    return self; 
} 

- (void)presentAtPoint:(CGPoint)loc 
{ 
    CGPoint newPoint = [self.container convertPoint:loc toView:self.container]; 

    self.content.center = newPoint; 
    [self.container addSubview:self.content]; 

} 


- (void)dismissMe:(UITapGestureRecognizer*)recognizer 
{ 
    //this never happens - I get EXC_BAD_ACCESS when I tap the overlay 
} 

回答

1

HelperView不是顯示的視圖,它沒有被保留,但是你用作目標f或手勢識別器。 AGWindowView屬性「容器」通過其超級視圖顯示並保留。你的代碼需要重構,因爲你有這個視圖HelperView本身沒有顯示任何東西,但是如果你希望它像這樣工作,你需要保留HelperView,以免它自動釋放。您可以通過將其分配給強實例變量來完成此操作。

+0

感謝您的信息。這就是我所想的。但是我希望這個HelperView能夠在我需要的時候創建,並且我不希望每個視圖控制器都要求有一個強大的實例變量。例如,UIAlertView不需要強大的實例變量。我如何保留一個獨立的視圖? – soleil

+0

另一個例子是這樣的:https://github.com/chrismiles/CMPopTipView。我已經看過代碼,但我不知道它是如何保留的。 – soleil

+0

把'[self.container addSubview:self.content]'改成'[self.container addSubview:self]',你會沒事的,除了內存泄漏。 –

相關問題