我正在为我的应用编写自定义UIButton
。但是,我想为按钮添加完整的操作。这样我就可以从动作中返回BOOL
,然后在按钮中执行一些代码(即显示动画),然后调用完成方法。
所以,理想情况下,我希望能够做到这样的事情:
[button addAction:^(){
NSLog(@"Action!");
return true;
} completion:^() {
NSLog(@"Completion!");
return true;
} forControlEvents:UIControlEventTouchUpInside];
如何覆盖UIControlEventTouchUpInside
发生时会发生什么?或者是另一个有争议的问题。
答案 0 :(得分:0)
您可以通过以下方式实现此目的:
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