2013-11-26 82 views
4

我已經創建了一個按鈕的自定義標註視圖。點擊Mapview上的任何註釋後,都會顯示此自定義標註。但是,當我點擊自定義標註內的按鈕時沒有任何反應。IBAction不會調用UIView中的按鈕

#import <UIKit/UIKit.h> 

@interface TestView : UIView 


@end 

#import "TestView.h" 

@implementation TestView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

-(IBAction)showMessage:(id)sender 
{ 
    NSLog(@"Test"); 
} 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 
} 
*/ 

@end 

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { 
    if(![view.annotation isKindOfClass:[MKUserLocation class]]) { 

     CGRect rect = CGRectMake(0,0,268,140); 

     TestView *testview = [[TestView alloc] initWithFrame:rect]; 

     testview = [self loadNibNamed:@"TestView" ofClass:[TestView class]]; 


     [view addSubview:testview]; 
    } 
} 

視圖使用loadNibNamed方法加載。

- (id)loadNibNamed:(NSString *)nibName ofClass:(Class)objClass { 
    if (nibName && objClass) { 
     NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil]; 

     for (id currentObject in objects){ 
      if ([currentObject isKindOfClass:objClass]) 
       return currentObject; 
     } 
    } 

    return nil; 
} 

enter image description here

我已經檢查了查看和按鈕的userInteractionEnabled財產,都被設置爲true。

還用Touch Up Inside事件按鈕映射了showMessage。

有關我如何識別此問題的任何建議?

+0

一個常見的錯誤是根本無法正確地內連接IB的動作。你檢查過了嗎? – trojanfoe

+0

謝謝我檢查過,包括相同的截圖。 – rshankar

+0

我剛發現這個錯誤,[view addSubview:testview];應該用[mapView addSubview:testview]替換;謝謝您的幫助。 – rshankar

回答

3

嘗試使用下面的靜態方法來獲取TestView

+ (TestView *)getNewTestView { 
    TestView *view = nil; 
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"TestView" owner:nil options:nil]; 
    for (NSObject *obj in xib) { 
     if ([obj isKindOfClass:[TestView class]]) { 
      view = (TestView *)obj; 
     } 
    } 
    return view; 

}

,然後獲取對象的實例,使用:

TestView *testView = [TestView getNewTestView]; 
[self.view addSubview:testView]; 
+0

添加到self.view實際上解決了問題,並且看起來是正確的方式。所以我接受了這個解決方案。謝謝 – rshankar

0

請確保您的MKAnnotationView有足夠的空間來填充testView。
如果它比testView小,外層空間將不會響應任何操作。
您可以將clipsToBounds設置爲NO來檢查實際空間。

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { 
if(![view.annotation isKindOfClass:[MKUserLocation class]]) { 
    view.clipsToBounds = NO; 
    CGRect rect = CGRectMake(0,0,268,140); 

    TestView *testview = [[TestView alloc] initWithFrame:rect]; 

    testview = [self loadNibNamed:@"TestView" ofClass:[TestView class]]; 


    [view addSubview:testview]; 
} 

}