3

我正在寻找编写自己的界面对象的正确方法。

说,我想要一个可以双击的图像。

@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;

这似乎是设计对象的正确方法。该按钮只知道它是否被双击,然后告诉代表谁决定如何处理这些信息。

我想知道是否有其他方法可以考虑这个问题?我注意到 UIButton 使用 UIController 和 addTarget: 来管理发送事件。在编写我自己的界面对象时是否希望利用这个系统?

更新:另一种技术是使用 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];

这种方法有什么缺点?更少的编译时检查,以及在对象结构之外飞来飞去的事件的潜在意大利面条代码?(如果两个开发人员使用相同的事件名称,甚至命名空间冲突?)

4

2 回答 2

2

代表绝对是去这里的方式。

于 2009-01-26T18:29:51.877 回答
1

或子类化UIControl并使用-sendActionsForControlEvents:. 这样做的主要优点是针对特定操作的多个目标……在这种情况下,当然,你只有双击,但我认为这是总体上最好的方法。

于 2009-01-26T18:34:46.063 回答