【问题标题】:iOS: How to correctly implement custom gesture recognizer in super class?iOS:如何在超类中正确实现自定义手势识别器?
【发布时间】:2015-11-02 21:48:46
【问题描述】:

只要用户用手指按下按钮,我的 iOS8+ 应用程序中的按钮就会通过在按钮周围绘制轮廓来做出反应。目标是将此行为封装到OutlineButton 类中(cp. 在类层次结构下)。当释放手指时,应用程序应该执行定义的动作(主要是执行到另一个视图控制器的 segue)。这是我当前的类层次结构:

 - UIButton
  |_ OutlineButton
    |_ FlipButton

FlipButton 类执行一些花哨的翻转效果,另外我在 UIView 上有一个用于投影、圆角和轮廓的类别。

目前我有以下附加课程:

#import <UIKit/UIKit.h>

@interface TouchDownGestureRecognizer : UIGestureRecognizer

@end

...以及相应的实现:

#import "UIView+Extension.h"
#import "TouchDownGestureRecognizer.h"

@implementation TouchDownGestureRecognizer

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view showOutline]; // this is a function in the UIView category (cp. next code section)
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view hideOutline]; // this is a function in the UIView category (cp. next code section)
}

@end

...这是 UIView+Extension.m 类别的相关sn-p,用于在按钮上绘制轮廓:

- (void)showOutline {
    self.layer.borderColor = [UIColor whiteColor].CGColor;
    self.layer.borderWidth = 1.0f;
}

- (void)hideOutline {
    self.layer.borderColor = [UIColor clearColor].CGColor;
}

...在 OutlineButton.m 文件中,到目前为止我有以下内容:

#import "OutlineButton.h"

@implementation OutlineButton

- (id)initWithCoder:(NSCoder*)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addGestureRecognizer:[[TouchDownGestureRecognizer alloc] init]];
    }
    return self;
}

@end

在视觉上,这很好用,只要触摸一个按钮,一旦松开手指,就会绘制轮廓并再次隐藏。但是如果有的话,通过故事板连接到这些按钮的 IBAction 和 segue 会在一个巨大的延迟(大约 2 秒)之后执行。如果按钮被多次按下(...经过长时间的延迟),这些操作也会执行多次。真是奇怪的行为......

有人知道如何解决这个问题吗?

解决方案(基于马特的回答,谢谢):

#import "OutlineButton.h"
#import "UIView+Extension.h"

@implementation OutlineButton

- (id)initWithCoder:(NSCoder*)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addTarget:self action:@selector(showOutline) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(hideOutline) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
    }
    return self;
}

@end

【问题讨论】:

    标签: ios uigesturerecognizer uitapgesturerecognizer gesture-recognition


    【解决方案1】:

    只要用户用手指按下按钮,我的 iOS8+ 应用程序中的按钮就会通过在按钮周围绘制轮廓来做出反应

    最符合框架的实现方式是为按钮分配一个具有轮廓的图像,用于突出显示状态。当按钮被按下时,它被突出显示;因此,只有在按下按钮时才会显示轮廓。

    【讨论】:

    • 感谢您的快速响应。如果除了为轮廓制作图像之外还有其他方法,我更愿意...您建议的实现可能很简单,但是为每个可能的尺寸管理图像,我的按钮最终会变得一团糟。因此,将高度赞赏问题中描述的另一种方法。超类中的自定义手势识别器真的会把响应者链弄得那么难吗?
    • 你只是在傻。没有“图像”需要“管理”。看看我回答中的截屏视频。这里没有使用“图像”;矩形是根据按钮的大小在代码中创建和分配的。
    • 好的,我明白了,你的措辞有点尴尬......我根据你的回答用正确的代码 sn-p 扩展了我的问题。谢谢。
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多