【问题标题】:Is there a way to call the TouchUpInside action in a custom UIButton?有没有办法在自定义 UIButton 中调用 TouchUpInside 操作?
【发布时间】:2017-05-19 11:54:30
【问题描述】:

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

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

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

如何覆盖UIControlEventTouchUpInside 发生时发生的情况?或者其他相关的控制事件。

【问题讨论】:

  • 您需要的信息在UIControl 参考/编程指南中。它不是特定于UIButton。 Apple 的搜索现在很糟糕,所以我无法快速找到/粘贴任何内容,但这将为您指明正确的方向。

标签: ios objective-c uibutton


【解决方案1】:

您可以通过以下方式实现此目的:

自定义按钮.h

@interface CustomButton : UIButton
- (void)addAction:(void (^)(CustomButton *button))action onCompletion:(void (^)(CustomButton *button))completion forControlEvents:(UIControlEvents)event;
@end

自定义按钮.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

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2011-04-15
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多