2009-01-26 49 views
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]; 

這種方法的缺點是什麼?減少編譯時檢查,以及事件在對象結構外飛行的潛在意大利麪代碼? (甚至命名空間碰撞,如果兩個開發人員使用相同的事件名稱?)

回答

2

委託是肯定的方式去這裏。

1

或子類UIControl和使用-sendActionsForControlEvents:。主要優點是針對特定動作的多個目標......在這種情況下,當然,您只能得到雙擊,但我認爲這是最好的方式。

+0

UIControl的問題在於UIControlEvents的數量有限 - TouchUpInside等。我看不到如何定義新事件,如「DoubleTap」。 – 2009-01-26 19:28:18