我的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类别的相关片段:
- (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