我想要一个可以双击的图像。
@interface DoubleTapButtonView : UIView {
UILabel *text;
UIImage *button;
UIImage *button_selected;
BOOL selected;
}
// detect tapCount == 2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
我的问题是如何干净利落地处理行动。我尝试过的两种方法是添加对父对象的引用和委托。
传递对父对象的引用非常简单。。。
@interface DoubleTapButtonView : UIView {
UILabel *text;
UIImage *button;
UIImage *button_selected;
BOOL selected;
MainViewController *parentView; // added
}
@property (nonatomic,retain) MainViewController *parentView; // added
// parentView would be assigned during init...
- (id)initWithFrame:(CGRect)frame
ViewController:(MainViewController *)aController;
- (id)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
但是,这将阻止我的DoubleTapButtonView类很容易添加到其他视图和视图控制器中。
委托给代码添加了一些额外的抽象,但它允许我在任何适合委托接口的类中使用DoubleTapButtonView。
@interface DoubleTapButtonView : UIView {
UILabel *text;
UIImage *button;
UIImage *button_selected;
BOOL selected;
id <DoubleTapViewDelegate> delegate;
}
@property (nonatomic,assign) id <DoubleTapViewDelegate> delegate;
@protocol DoubleTapViewDelegate <NSObject>
@required
- (void)doubleTapReceived:(DoubleTapView *)target;
这似乎是设计对象的正确方法。按钮只知道它是否被双击,然后告诉代表谁决定如何处理这些信息。
更新:另一种技术是使用NSNotificationCenter为各种事件创建观察者,然后在按钮中创建事件。
// listen for the event in the parent object (viewController, etc)
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(DoubleTapped:)
name:@"DoubleTapNotification" object:nil];
// in DoubleTapButton, fire off a notification...
[[NSNotificationCenter defaultCenter]
postNotificationName:@"DoubleTapNotification" object:self];
这种方法的缺点是什么?更少的编译时检查,以及事件在对象结构外部飞来飞去的潜在的意大利面代码?(如果两个开发人员使用相同的事件名称,甚至会发生命名空间冲突?)