你可以做一些像實現這一目標:
CustomButton.h
@interface CustomButton : UIButton
- (void)addAction:(void (^)(CustomButton *button))action onCompletion:(void (^)(CustomButton *button))completion forControlEvents:(UIControlEvents)event;
@end
CustomButton.m
#import "CustomButton.h"
@interface CustomButton()
@property (nonatomic, copy) void(^actionHandler)(CustomButton *button);
@property (nonatomic, copy) void(^completionHandler)(CustomButton *button);
@end
@implementation CustomButton
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (void)addAction:(void (^)(CustomButton *button))action onCompletion:(void (^)(CustomButton *button))completion forControlEvents:(UIControlEvents)event
{
self.actionHandler = action;
self.completionHandler = completion;
__weak __typeof__(self) weakSelf = self;
[self addTarget:weakSelf action:@selector(buttonAction) forControlEvents:event];
}
- (void)buttonAction
{
if (self.actionHandler) {
self.actionHandler(self);
}
// This will execute right after executing action handler.
// NOTE: If action handler is dispatching task, then execution of completionHandler will not wait for completion of dispatched task
// that should handled using some notification/kvo.
if (self.completionHandler) {
self.completionHandler(self);
}
}
@end
你需要的信息是'UIControl'參考/編程指南。它不是特定於'UIButton'。蘋果的搜索現在很糟糕,所以我無法快速找到/粘貼任何東西,但這會讓您指向正確的方向。 –