본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Gestures (제스처)

원문 보기 위키 갱신

Ionic Gestures는 개발자가 플랫폼에 구애받지 않는 방식으로 앱을 위한 사용자 지정 제스처와 상호작용을 만들 수 있게 해주는 유틸리티입니다. React나 Angular 같은 특정 프레임워크를 사용할 필요도 없고, 심지어 Ionic 앱을 만들고 있지 않아도 됩니다. 개발자가 Ionic Framework v5.0 이상을 사용할 수 있다면 Ionic Gestures의 모든 기능을 사용할 수 있습니다.

출처: 문서

본문

Overview (개요)

복잡한 제스처를 만드는 것은 시간이 많이 걸리는 작업입니다. 사용자 지정 제스처를 제공하는 다른 라이브러리들은 종종 너무 과하게 개입해서 마우스 또는 터치 이벤트를 잡아버리고 그 이벤트들이 전파되지 못하게 막기도 합니다. 그러면 다른 요소들이 더는 스크롤하거나 클릭할 수 없게 될 수 있습니다.

Installation (설치)

Ionic Core와 JavaScript를 사용하는 개발자는 최신 버전의 @ionic/core를 설치해야 합니다.

import { createGesture } from 'https://cdn.jsdelivr.net/npm/@ionic/core@latest/dist/esm/index.mjs';

...

const gesture = createGesture({
  el: elementRef,
  threshold: 15,
  gestureName: 'my-gesture',
  onMove: event => onMoveHandler(event)
});

Ionic Core와 TypeScript를 사용하는 개발자는 최신 버전의 @ionic/core를 설치해야 합니다.

import { createGesture, Gesture } from '@ionic/core';

...

const gesture: Gesture = createGesture({
  el: elementRef,
  threshold: 15,
  gestureName: 'my-gesture',
  onMove: event => onMoveHandler(event)
});

Angular를 사용하는 개발자는 최신 버전의 @ionic/angular를 설치해야 합니다. 제스처는 GestureController 의존성 주입을 통해 만들 수 있습니다. 기본적으로 제스처 콜백은 NgZone 안에서 실행되지 않습니다. 개발자는 제스처를 만들 때 runInsideAngularZone 파라미터를 true로 설정하거나, 콜백을 NgZone.run() 호출로 감쌀 수 있습니다.

import { Gesture, GestureController } from '@ionic/angular/lazy';

...

constructor(private gestureCtrl: GestureController) {
  const gesture: Gesture = this.gestureCtrl.create({
    el: this.element.nativeElement,
    threshold: 15,
    gestureName: 'my-gesture',
    onMove: event => this.onMoveHandler(event)
  }, true);
  // The `true` above ensures that callbacks run inside NgZone.
}

Angular를 사용하는 개발자는 최신 버전의 @ionic/angular를 설치해야 합니다. 제스처는 GestureController 의존성 주입을 통해 만들 수 있습니다. 기본적으로 제스처 콜백은 NgZone 안에서 실행되지 않습니다. 개발자는 제스처를 만들 때 runInsideAngularZone 파라미터를 true로 설정하거나, 콜백을 NgZone.run() 호출로 감쌀 수 있습니다.

import { Gesture, GestureController } from '@ionic/angular';

...

constructor(private gestureCtrl: GestureController) {
  const gesture: Gesture = this.gestureCtrl.create({
    el: this.element.nativeElement,
    threshold: 15,
    gestureName: 'my-gesture',
    onMove: event => this.onMoveHandler(event)
  }, true);
  // The `true` above ensures that callbacks run inside NgZone.
}

React를 사용하는 개발자는 최신 버전의 @ionic/react를 설치해야 합니다.

import { createGesture, Gesture } from '@ionic/react';

...

const gesture: Gesture = createGesture({
  el: elementRef,
  threshold: 15,
  gestureName: 'my-gesture',
  onMove: event => onMoveHandler(event)
});

Ionic Vue를 사용하는 개발자는 최신 버전의 @ionic/vue를 설치해야 합니다.

import { createGesture } from '@ionic/vue';
import { ref } from 'vue';

...

const elementRef = ref();

...

const gesture = createGesture({
  el: elementRef.value,
  threshold: 15,
  gestureName: 'my-gesture',
  onMove: event => onMoveHandler(event)
});

Basic Gestures (기본 제스처)

이 예제에서 우리 앱은 ion-content 요소에서 제스처를 감지합니다. 제스처 움직임이 시작되면 onStart 함수가 호출되어 ion-card에 색상이 있는 box-shadow를 추가하는 클래스가 부여됩니다. 제스처 움직임이 감지되면 onMove 함수가 호출되어 앱이 현재 제스처 정보를 ion-card 안에 출력합니다. 마지막으로 제스처 움직임이 끝나면 onEnd 함수가 호출되어 ion-card에서 사용자 지정 클래스가 제거됩니다.

JavaScript

<style>
  ion-card {
    position: absolute;

    left: 0;
    right: 0;

    user-select: none;
  }

  ion-card.active {
    box-shadow: var(--ion-color-warning) 0px 4px 16px;
  }
</style>

<ion-card>
  <ion-card-header>
    <ion-card-subtitle>Pan the Screen</ion-card-subtitle>
  </ion-card-header>
  <ion-card-content>
    <p id="debug">Gesture information will display after interaction.</p>
  </ion-card-content>
</ion-card>

<script>
  const p = document.querySelector('#debug');
  const target = document.querySelector('ion-content');
  const card = document.querySelector('ion-card');

  const onMove = (detail) => {
    const { type, currentX, deltaX, velocityX } = detail;
    p.innerHTML = `
    <div>Type: ${type}</div>
    <div>Current X: ${currentX}</div>
    <div>Delta X: ${deltaX}</div>
    <div>Velocity X: ${velocityX}</div>`;
  };

  const onStart = () => {
    card.classList.add('active');
  };

  const onEnd = () => {
    card.classList.remove('active');
  };

  const gesture = createGesture({
    el: target,
    onStart,
    onMove,
    onEnd,
    gestureName: 'example',
  });

  gesture.enable();
</script>

Angular

src/app/example.component.html

<ion-card [class.active]="isCardActive">
  <ion-card-header>
    <ion-card-subtitle>Pan the Screen</ion-card-subtitle>
  </ion-card-header>
  <ion-card-content>
    <p #debug>Gesture information will display after interaction.</p>
  </ion-card-content>
</ion-card>

src/app/example.component.ts

import { ChangeDetectorRef, Component, ElementRef, ViewChild } from '@angular/core';
import { GestureController, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle } from '@ionic/angular';
import type { GestureDetail } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonCard, IonCardContent, IonCardHeader, IonCardSubtitle],
})
export class ExampleComponent {
  @ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;
  @ViewChild('debug', { read: ElementRef }) debug!: ElementRef<HTMLParagraphElement>;

  isCardActive = false;

  constructor(
    private el: ElementRef,
    private gestureCtrl: GestureController,
    private cdRef: ChangeDetectorRef
  ) {}

  ngAfterViewInit() {
    const gesture = this.gestureCtrl.create({
      el: this.el.nativeElement.closest('ion-content'),
      onStart: () => this.onStart(),
      onMove: (detail) => this.onMove(detail),
      onEnd: () => this.onEnd(),
      gestureName: 'example',
    });

    gesture.enable();
  }

  private onStart() {
    this.isCardActive = true;
    this.cdRef.detectChanges();
  }

  private onMove(detail: GestureDetail) {
    const { type, currentX, deltaX, velocityX } = detail;
    this.debug.nativeElement.innerHTML = `
      <div>Type: ${type}</div>
      <div>Current X: ${currentX}</div>
      <div>Delta X: ${deltaX}</div>
      <div>Velocity X: ${velocityX}</div>`;
  }

  private onEnd() {
    this.isCardActive = false;
    this.cdRef.detectChanges();
  }
}

src/app/example.component.css

ion-card {
  position: absolute;

  left: 0;
  right: 0;

  user-select: none;
}

ion-card.active {
  box-shadow: var(--ion-color-warning) 0px 4px 16px;
}

React

src/main.tsx

import React, { useEffect, useRef } from 'react';
import { IonCard, IonCardHeader, IonCardSubtitle, IonCardContent, createGesture } from '@ionic/react';
import type { GestureDetail } from '@ionic/react';

import './main.css';

function Example() {
  const card = useRef<HTMLIonCardElement | null>(null);
  const debug = useRef<HTMLParagraphElement | null>(null);

  useEffect(() => {
    if (card.current) {
      const target = card.current.closest('ion-content');

      if (target) {
        const gesture = createGesture({
          el: target,
          onStart: () => onStart(),
          onMove: (detail) => onMove(detail),
          onEnd: () => onEnd(),
          gestureName: 'example',
        });

        gesture.enable();
      }
    }
  }, [card]);

  const onStart = () => {
    card.current?.classList.add('active');
  };

  const onMove = (detail: GestureDetail) => {
    const { type, currentX, deltaX, velocityX } = detail;

    if (debug.current) {
      debug.current.innerHTML = `
        <div>Type: ${type}</div>
        <div>Current X: ${currentX}</div>
        <div>Delta X: ${deltaX}</div>
        <div>Velocity X: ${velocityX}</div>`;
    }
  };

  const onEnd = () => {
    card.current?.classList.remove('active');
  };

  return (
    <IonCard ref={card}>
      <IonCardHeader>
        <IonCardSubtitle>Pan the Screen</IonCardSubtitle>
      </IonCardHeader>
      <IonCardContent>
        <p ref={debug}>Gesture information will display after interaction.</p>
      </IonCardContent>
    </IonCard>
  );
}
export default Example;

src/main.css

ion-card {
  position: absolute;

  left: 0;
  right: 0;

  user-select: none;
}

ion-card.active {
  box-shadow: var(--ion-color-warning) 0px 4px 16px;
}

Vue

<style scoped>
  ion-card {
    position: absolute;

    left: 0;
    right: 0;

    user-select: none;
  }

  ion-card.active {
    box-shadow: var(--ion-color-warning) 0px 4px 16px;
  }
</style>
<template>
  <ion-card ref="card">
    <ion-card-header>
      <ion-card-subtitle>Pan the Screen</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      <p ref="debug">Gesture information will display after interaction.</p>
    </ion-card-content>
  </ion-card>
</template>

<script setup lang="ts">
  import { IonButton, IonCard, IonCardContent, createGesture } from '@ionic/vue';
  import type { GestureDetail } from '@ionic/vue';
  import { ref, onMounted } from 'vue';

  const card = ref(null);
  const debug = ref(null);

  onMounted(() => {
    const gesture = createGesture({
      el: card.value.$el.closest('ion-content'),
      onStart: () => onStart(),
      onMove: (detail) => onMove(detail),
      onEnd: () => onEnd(),
      gestureName: 'example',
    });

    gesture.enable();
  });

  const onStart = () => {
    card.value?.$el.classList.add('active');
  };

  const onMove = (detail: GestureDetail) => {
    const { type, currentX, deltaX, velocityX } = detail;

    if (debug.value) {
      debug.value.innerHTML = `
      <div>Type: ${type}</div>
      <div>Current X: ${currentX}</div>
      <div>Delta X: ${deltaX}</div>
      <div>Velocity X: ${velocityX}</div>`;
    }
  };

  const onEnd = () => {
    card.value?.$el.classList.remove('active');
  };
</script>

Double Click Gesture (더블 클릭 제스처)

아래 예제에서는 요소의 더블 클릭을 감지하려고 합니다. threshold를 0으로 설정하면 제스처 객체가 클릭을 감지할 수 있게 됩니다. 또한 클릭 간격 기준(click threshold)을 정의해서 빠르게 연속으로 발생하는 2번의 클릭만 더블 클릭으로 간주하도록 합니다.

JavaScript

<ion-card>
  <ion-card-content>Double click me to move the card.</ion-card-content>
</ion-card>

<style>
  ion-card {
    transform: translateX(0);
    user-select: none;
  }
</style>

<script>
  const DOUBLE_CLICK_THRESHOLD = 500;
  const card = document.querySelector('ion-card');
  const gesture = createGesture({
    el: card,
    threshold: 0,
    onStart: () => onStart(),
    gestureName: 'double-click',
  });

  gesture.enable();

  let lastOnStart = 0;
  let currentOffset = 0;

  const onStart = () => {
    const now = Date.now();

    if (Math.abs(now - lastOnStart) <= DOUBLE_CLICK_THRESHOLD) {
      card.style.setProperty('transform', getNewTransform());
      lastOnStart = 0;
    } else {
      lastOnStart = now;
    }
  };

  const getNewTransform = () => {
    if (currentOffset >= 100) {
      currentOffset = 0;
    } else {
      currentOffset += 20;
    }

    return `translateX(${currentOffset}px)`;
  };
</script>

Angular

src/app/example.component.html

<ion-card #card>
  <ion-card-content>Double click me to move the card.</ion-card-content>
</ion-card>

src/app/example.component.ts

import { Component, ElementRef, ViewChild } from '@angular/core';
import { GestureController, IonCard, IonCardContent } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['./example.component.css'],
  imports: [IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChild('card', { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;

  private currentOffset: number = 0;
  private lastOnStart: number = 0;
  private DOUBLE_CLICK_THRESHOLD: number = 500;

  constructor(
    private el: ElementRef,
    private gestureCtrl: GestureController
  ) {}

  ngAfterViewInit() {
    const gesture = this.gestureCtrl.create({
      el: this.card.nativeElement,
      threshold: 0,
      onStart: () => this.onStart(),
      gestureName: 'double-click',
    });

    gesture.enable();
  }

  private onStart() {
    const now = Date.now();

    if (Math.abs(now - this.lastOnStart) <= this.DOUBLE_CLICK_THRESHOLD) {
      this.card.nativeElement.style.setProperty('transform', this.getNewTransform());
      this.lastOnStart = 0;
    } else {
      this.lastOnStart = now;
    }
  }

  private getNewTransform() {
    if (this.currentOffset >= 100) {
      this.currentOffset = 0;
    } else {
      this.currentOffset += 20;
    }

    return `translateX(${this.currentOffset}px)`;
  }
}

src/app/example.component.css

ion-card {
  transform: translateX(0);
  user-select: none;
}

React

src/main.tsx

import React, { useEffect, useRef } from 'react';
import { IonCard, IonCardContent, createGesture } from '@ionic/react';

import './main.css';

function Example() {
  const DOUBLE_CLICK_THRESHOLD = 500;
  const card = useRef<HTMLIonCardElement | null>(null);

  let lastOnStart = 0;
  let currentOffset = 0;

  const getNewTransform = () => {
    if (currentOffset >= 100) {
      currentOffset = 0;
    } else {
      currentOffset += 20;
    }

    return `translateX(${currentOffset}px)`;
  };

  const onStart = () => {
    const now = Date.now();

    if (Math.abs(now - lastOnStart) <= DOUBLE_CLICK_THRESHOLD) {
      if (card.current) {
        card.current.style.setProperty('transform', getNewTransform());
        lastOnStart = 0;
      }
    } else {
      lastOnStart = now;
    }
  };

  useEffect(() => {
    if (card.current) {
      const gesture = createGesture({
        el: card.current,
        threshold: 0,
        onStart,
        gestureName: 'double-click',
      });

      gesture.enable();
    }
  });

  return (
    <IonCard ref={card}>
      <IonCardContent>Double click me to move the card.</IonCardContent>
    </IonCard>
  );
}
export default Example;

src/main.css

ion-card {
  transform: translateX(0);
  user-select: none;
}

Vue

<template>
  <ion-card ref="card">
    <ion-card-content>Double click me to move the card.</ion-card-content>
  </ion-card>
</template>

<script setup lang="ts">
  import { IonCard, IonCardContent, createGesture } from '@ionic/vue';
  import { onMounted, ref } from 'vue';

  const DOUBLE_CLICK_THRESHOLD = 500;
  const card = ref();

  let lastOnStart = 0;
  let currentOffset = 0;

  onMounted(() => {
    const gesture = createGesture({
      el: card.value.$el,
      threshold: 0,
      onStart,
      gestureName: 'double-click',
    });

    gesture.enable();
  });

  const onStart = () => {
    const now = Date.now();

    if (Math.abs(now - lastOnStart) <= DOUBLE_CLICK_THRESHOLD) {
      card.value.$el.style.setProperty('transform', getNewTransform());
      lastOnStart = 0;
    } else {
      lastOnStart = now;
    }
  };

  const getNewTransform = () => {
    if (currentOffset >= 100) {
      currentOffset = 0;
    } else {
      currentOffset += 20;
    }

    return `translateX(${currentOffset}px)`;
  };
</script>

<style scoped>
  ion-card {
    transform: translateX(0);
    user-select: none;
  }
</style>

Gesture Animations (제스처 애니메이션)

제스처 애니메이션 구현 가이드를 참고하세요: Gesture Animations with Ionic Animations

Types (타입)

Name Value
GestureCallback (detail: GestureDetail) => boolean | void

Interfaces (인터페이스)

GestureConfig

Property Type Default Description
el Node undefined 제스처를 감지할 요소.
disableScroll boolean | undefined false true이면 제스처가 활성화되어 있는 동안 el에서 스크롤이 비활성화됩니다.
direction 'x' | 'y' | undefined 'x' 특정 축을 따라 움직이는 제스처만 감지하도록 제한합니다.
gestureName string undefined 만들 제스처의 이름.
gesturePriority number | undefined 0 우선순위가 더 높은 제스처는 더 낮은 제스처를 덮어씁니다. 여러 제스처가 서로 충돌하지 않도록 하는 데 유용합니다.
passive boolean | undefined true true이면 제스처가 결코 preventDefault()를 호출하지 않는다는 것을 나타냅니다. 이는 스크롤 성능을 개선하는 데 사용할 수 있습니다. 자세한 내용은 Passive Listeners를 참고하세요.
maxAngle number | undefined 40 제스처를 감지할 때 허용할 최대 각도.
threshold number | undefined 10 제스처가 시작되기 전에 포인터가 얼마나 움직여야 하는지 정의합니다.
blurOnStart boolean | undefined undefined true이면 onStart 콜백을 실행하기 전에 input이나 textarea 같은 활성 선택 가능 요소의 포커스(blur)를 해제합니다.
canStart GestureCallback | undefined undefined 제스처가 시작될 수 있으면 true를 반환하는 콜백.
onWillStart (detail: GestureDetail) => Promise<void> undefined 제스처가 시작하려 할 때 실행되는 콜백. canStart 이후, onStart 이전에 실행됩니다.
onStart GestureCallback | undefined undefined 제스처가 시작되었을 때 실행되는 콜백.
onMove GestureCallback | undefined undefined 제스처 움직임이 감지되었을 때 실행되는 콜백.
onEnd GestureCallback | undefined undefined 제스처가 끝났을 때 실행되는 콜백. 보통 포인터가 놓였을 때입니다.
notCaptured GestureCallback | undefined undefined 제스처가 캡처되지 않았을 때 실행되는 콜백. 보통 우선순위가 더 높은 충돌하는 제스처가 있을 때 발생합니다.

GestureDetail

Property Type Description
type string 감지된 제스처의 유형.
startX number 제스처의 시작 x 좌표.
startY number 제스처의 시작 y 좌표.
startTimeStamp number 제스처가 시작된 시각.
currentX number 제스처의 현재 x 좌표.
currentY number 제스처의 현재 y 좌표.
velocityX number 제스처가 현재 x 축에서 움직이는 속도.
velocityY number 제스처가 현재 y 축에서 움직이는 속도.
deltaX number 제스처가 시작된 이후 x 축에서 움직인 거리.
deltaY number 제스처가 시작된 이후 y 축에서 움직인 거리.
timeStamp number 제스처의 현재 시각.
event UIEvent 브라우저가 발생시킨 네이티브 이벤트. 자세한 내용은 UIEvent를 참고하세요.
data any | undefined 사용자가 지정한 모든 데이터. 어떤 콜백에서든 설정하고 읽을 수 있습니다.

Methods (메서드)

enable(enable: boolean = true) => void

제스처를 활성화하거나 비활성화합니다.

destroy() => void

제스처 인스턴스를 파괴하고 대상 요소에서 감지를 중지합니다.

더 알아보기 (Learn more)

이번에는 Ionic Gestures의 설치, 기본 제스처와 더블 클릭 제스처, 그리고 GestureConfig와 GestureDetail 인터페이스 및 메서드까지 살펴봤어요. 다음으로는 Ionic Animations 문서를 살펴보며 제스처와 애니메이션을 결합하는 방법을 다루어 보시길 권합니다.