我從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