有没有办法在自定义UIButton中调用TouchUpInside操作?

时间:2017-05-19 11:54:30

标签: ios objective-c uibutton

我正在为我的应用编写自定义UIButton。但是,我想为按钮添加完整的操作。这样我就可以从动作中返回BOOL,然后在按钮中执行一些代码(即显示动画),然后调用完成方法。

所以,理想情况下,我希望能够做到这样的事情:

[button addAction:^(){
    NSLog(@"Action!");
    return true;
} completion:^() {
    NSLog(@"Completion!");
    return true;
} forControlEvents:UIControlEventTouchUpInside];

如何覆盖UIControlEventTouchUpInside发生时会发生什么?或者是另一个有争议的问题。

1 个答案:

答案 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