Come creare un double tap button
giovedì 11 febbraio, 2010 di Giovambattista FazioliPrendendo spunto dall’articolo Come creare un proprio protocollo con delegato vediamo come creare una nostra classe bottone che risponde al doppio tap.
DoubleTapButtonView
Possiamo inserire questa classe in qualsiasi progetto, nuovo o vecchio. Il file .h è così configurato:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #import <UIKit/UIKit.h> @protocol DoubleTapButtonViewDelegate <NSObject> @optional - (void)didDoubleTap:(id)sender; @end @interface DoubleTapButtonView : UIView { id <DoubleTapButtonViewDelegate> delegate; } @property (assign) id <DoubleTapButtonViewDelegate> delegate; @end |
Abbiamo definito un nostro protocollo DoubleTapButtonViewDelegate e un nostro speciale evento didDoubleTap.
Nel file .m di implementazione:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #import "DoubleTapButtonView.h" @implementation DoubleTapButtonView @synthesize delegate; - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Initialization code } return self; } - (void)drawRect:(CGRect)rect { // Drawing code } #pragma mark - #pragma mark Touch Event - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"DoubleTapButtonView::touchesBegan()"); UITouch *touch = [touches anyObject]; if ([touch tapCount] == 2) { if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(didDoubleTap:)]) { [delegate didDoubleTap:self]; } } } - (void)dealloc { [super dealloc]; } @end |
L’evento touchesBegan ci permette di verificare il tipo di “tocco”; in questo caso controlliamo la proprietà tapCount dell’oggetto touch. Se viene rilevato un doppio-tap, allora l’evento didDoubleTap è inviato ai delegati.
Potete scaricare un progetto demo qui: DoubleTap.zip





Non ci sono commenti per questo Post
Lascia un commento