我从xib中创建了一个名为HeaderView的自定义UIView。我在这个HeaderView和按钮水龙头中有一个UIButton,我想要在添加HeaderView的ViewController上调用一个块。这是我的HeaderView的代码。目标C块变为无
头文件中的代码
@interface HeaderView : UIView
- (instancetype)initWithFrame:(CGRect)frame;
@property (copy) void(^seeAllHandler)();
@end
执行文件中的代码
@interface HeaderView()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *seeAllButton;
@property (nonatomic, strong) UIView *contentView;
@end
@implementation HeaderView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
}
return self;
}
- (void)awakeFromNib
{
[self.seeAllButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[self.seeAllButton setTitle:@"SEE ALL") forState:UIControlStateNormal];
[self.titleLabel setText:@"My Label")];
}
#pragma mark - Private methods
- (void)setup
{
//Setup view from the xib file.
self.contentView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
[self.contentView setFrame:self.bounds];
[self addSubview:self.contentView];
self.contentView.backgroundColor = [UIColor ccNordeaPink];
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.clipsToBounds = YES;
}
- (IBAction)sellAllTapped:(UIButton *)sender {
if(self.seeAllHandler != nil){
self.seeAllHandler();
}
}
@end
,这里是我的视图控制器viewDidLoad方法。
@interface ViewController() <UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) HeaderView *headerView;
@end
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupSubviews];
[self setupConstraints];
}
- (void)setupSubviews
{
self.headerView = [[HeaderView alloc] init ];
self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
self.headerView.seeAllHandler = ^{
DDLogDebug(@"See all Tapped");
};
[self.view addSubView: self.headerView];
}
问题是,当点击按钮时,分配的块是零,因此它不会被调用。
感谢很好解释。 – Madu