Ваш вид должен быть настроен на прием касаний ([self setAcceptsTouchEvents:YES]
). Когда вы получаете событие касания, например -touchesBeganWithEvent:
, вы можете определить, где находится палец, взглянув на его normalizedPosition
(диапазон [0,0, 1,0] x [0,0, 1,0]) в свете его deviceSize
в большом очки (есть 72 б.п. на дюйм). Нижний левый угол трекпада рассматривается как нулевое начало.
Так, например:
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (!self) return nil;
/* You need to set this to receive any touch event messages. */
[self setAcceptsTouchEvents:YES];
/* You only need to set this if you actually want resting touches.
* If you don't, a touch will "end" when it starts resting and
* "begin" again if it starts moving again. */
[self setWantsRestingTouches:YES]
return self;
}
/* One of many touch event handling methods. */
- (void)touchesBeganWithEvent:(NSEvent *)ev {
NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseBegan inView:self];
for (NSTouch *touch in touches) {
/* Once you have a touch, getting the position is dead simple. */
NSPoint fraction = touch.normalizedPosition;
NSSize whole = touch.deviceSize;
NSPoint wholeInches = {whole.width / 72.0, whole.height / 72.0};
NSPoint pos = wholeInches;
pos.x *= fraction.x;
pos.y *= fraction.y;
NSLog(@"%s: Finger is touching %g inches right and %g inches up "
@"from lower left corner of trackpad.", __func__, pos.x, pos.y);
}
}
(Рассматривайте этот код как иллюстрацию, а не как проверенный и верный, изношенный в бою пример кода; я просто написал его прямо в поле для комментариев.)