Cocoa 手勢支援

在 Macbook Air 推出之後,Apple 就多了手勢操作這項功能,但是這項功能雖然在 10.5 就有了,不過卻直到 10.6 才在 Apple 的 Document 中出現。而要在 10.5 中使用這項功能的話,其實也很簡單,只要實作 10.6 的 Document 裡面出現的幾項 method 即可,也就是下面五個 method:

- (void)magnifyWithEvent:(NSEvent *)event;
- (void)rotateWithEvent:(NSEvent *)event;
- (void)swipeWithEvent:(NSEvent *)event;
- (void)beginGestureWithEvent:(NSEvent *)event;
- (void)endGestureWithEvent:(NSEvent *)event;

不過除非要自己抓取新的手勢,不然主要只要實作 magnifyWithEvent、rotateWithEvent、swipeWithEvent 這三個即可。

這三個手勢的詳細操作,可以參考 10.6 的 Document,在 10.5 都相容,只有 magnifyWithEvent 要特別處理一下。

magnifyWithEvent 的標準用法如下(Apple Document):

- (void)magnifyWithEvent:(NSEvent *)event {  
 [resultsField setStringValue:  
 [NSString stringWithFormat:@"Magnification value is %f", [event magnification]]];  
 NSSize newSize;  
 newSize.height = self.frame.size.height * ([event magnification] + 1.0);  
 newSize.width = self.frame.size.width * ([event magnification] + 1.0);  
 [self setFrameSize:newSize];  
} 

但是在 10.5 上,NSEvent 沒有 magnification 這個 method,所以必須自己擴充,code 如下(ref):

#pragma mark defines for 10.6 api not documented in 10.5  
#ifndef MAC_OS_X_VERSION_10_6  
enum {  
 /* The following event types are available on some hardware on 10.5.2 and later */  
 NSEventTypeGesture = 29,  
 NSEventTypeMagnify = 30,  
 NSEventTypeSwipe = 31,  
 NSEventTypeRotate = 18,  
 NSEventTypeBeginGesture = 19,  
 NSEventTypeEndGesture = 20  
};  
  
@interface NSEvent(GestureEvents)  
/* This message is valid for events of type NSEventTypeMagnify, on 10.5.2 or later */  
#if MAC_OS_X_VERSION_MIN_REQUIRED   

這段 code 也把 10.5 中 NSEvent 欠缺的 type id 補齊了,所以如果想要支援手勢操作,最好都把這段 code 貼上來用吧。

Contents

comments powered by Disqus