在UIView内部没有调用IBAction

时间:2013-11-26 09:08:46

标签: ios objective-c uiview

我已经使用按钮为自定义标注创建了一个视图。单击Mapview上的任何注释即可显示此自定义标注。但是当我点击自定义标注内的按钮时没有任何反应。

#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

我检查了View和Button的userInteractionEnabled属性,两者都设置为true。

还使用按钮的Touch Up Inside事件映射showMessage。

关于如何识别此问题的任何建议?

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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];
}

}