3

独自のインターフェイス オブジェクトを作成する正しい方法を探しています。

たとえば、ダブルタップできる画像が欲しい。

@interface DoubleTapButtonView : UIView {
    UILabel *text;
    UIImage *button;
    UIImage *button_selected;
    BOOL selected;
}
// detect tapCount == 2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

これは問題なく動作します。ボタンはイベントを受け取り、ダブルタップを検出できます。

私の質問は、アクションをきれいに処理する方法です。私が試した 2 つのアプローチは、親オブジェクトと委任への参照を追加することです。

親オブジェクトへの参照を渡すのは非常に簡単です...

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

このアプローチの欠点は何ですか? コンパイル時のチェックが減り、イベントがオブジェクト構造の外を飛び回るスパゲッティ コードになる可能性はありますか? (さらに、2 人の開発者が同じイベント名を使用している場合、名前空間の衝突も?)

4

2 に答える 2

2

デリゲートは間違いなくここに行く方法です。

于 2009-01-26T18:29:51.877 に答える
1

またはサブクラス化UIControlして使用します-sendActionsForControlEvents:。その主な利点は、特定のアクションの複数のターゲットです...この場合、もちろん、ダブルタップしかありませんが、一般的にはそれが最善の方法だと思います.

于 2009-01-26T18:34:46.063 に答える