编辑我有 .xib 文件UIView
。UIView
包含一些元素和点击手势识别器。
AnnotationView
它与插座相连。在AnnotationView
,我正在捕捉点击事件,它工作正常。
然后我试图将此事件传递给我的父视图(ViewController
),其中AnnotationView
实例被创建并添加为子视图。但是我的委托方法没有被调用。我不知道,如何解决这个问题,也不知道是因为我使用的是 subview 还是我只是对委托做错了什么。
这是一些代码:
注释视图.h
#import <UIKit/UIKit.h>
@protocol protName <NSObject>
-(void) test;
@end
@interface AnnotationView : UIView
@property (strong, nonatomic) IBOutlet UIImageView *image;
@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@property (weak, nonatomic) IBOutlet UILabel *accessoryLabel;
@property (strong, nonatomic) IBOutlet UITapGestureRecognizer *tapRecognizer;
@property (nonatomic, weak) id <protName> delegate;
-(IBAction)handleTap:(UITapGestureRecognizer *)tapRecognizer;
@end
注释视图.m
#import "AnnotationView.h"
@implementation AnnotationView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"AnnotationView"
owner:self
options:nil];
AnnotationView *_myView = [nibContents objectAtIndex:0];
_myView.backgroundColor = [UIColor greenColor];
[self addSubview: _myView];
}
return self;
}
-(IBAction)handleTap:(UITapGestureRecognizer *)tapRecognizer{
NSLog(@"tap tap");
[self.delegate test]; //this delegate is nil
}
@end
视图控制器.h
#import <UIKit/UIKit.h>
#import "AnnotationView.h"
@interface ViewController : UIViewController <protName>
@property (nonatomic,retain) AnnotationView *annot;
-(void) test;
@end
视图控制器.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
_annot = [[AnnotationView alloc] initWithFrame:CGRectMake(100, 100, 212, 45)];
_annot.textLabel.text = @"some text";
_annot.delegate = self;
[self.view addSubview:_annot];
}
-(void) viewWillAppear:(BOOL)animated{
_annot.delegate = self;
}
-(void) test{
NSLog(@"Delegate massage is received!");
}
@end