【发布时间】: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