Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - SwiftUI] DragGesture 사용 방법 (뷰 드래그, 뷰 이동 방법, .gesture()) 본문

iOS 응용 (SwiftUI)

[iOS - SwiftUI] DragGesture 사용 방법 (뷰 드래그, 뷰 이동 방법, .gesture())

jake-kim 2022. 9. 29. 23:21

DragGesture

https://developer.apple.com/documentation/swiftui/draggesture

  • drag 관련 액션 이벤트를 생성할때 사용
  • View 프로토콜을 따르고 있는 모든 곳에 .gesture()를 추가할 수 있는데, 이 gesture안에 들어가는 인스턴스가 DragGesture

  • DragGesture()인스턴스에 onChanged, onEnded를 사용하여 드래그 이벤트 처리
  var body: some View {
    Button("SomeButton") {
      print("tap button")
    }
    .gesture(
      DragGesture()
        .onChanged { gesture in  }
        .onEnded { gesture in  }
    )
  }

뷰 드래그 구현 방법

  • 프로퍼티 정의
    • draggedOffset: 드래그한 만큼 뷰가 움직이도록 binding에 사용될 프로퍼티
    • accumlatedOffset: 지금까지 드래그 된 값을 기록하고 있는 프로퍼티
struct ContentView: View {
  @State private var draggedOffset = CGSize.zero
  @State private var accumulatedOffset = CGSize.zero
  
  var body: some View {
  
  }
}
  • 예제로 사용할 Circle() 뷰 준비
    • 포인트1) .offset()으로 지금 드래그된 만큼 뷰가 이동하도록 바인딩
    • 포인트2) .gesture()에 DragGesture 인스턴스를 넣는데, 이 안에는 Gesture 프로토콜을 따르는 모든 인스턴스가 들어갈 수 있으므로, some Gesture를 반환하는 프로퍼티를 사용
  var body: some View {
    Circle()
      .foregroundColor(Color.blue)
      .frame(width: 100, height: 100)
      .offset(draggedOffset)
      .gesture(drag)
  }
  
  var drag: some Gesture {
  	// TODO
  }
  • drag 구현
    • 편리를 위해 CGSize(width:height:)값에서 각각 더하는 Operator도 CGSize를 extension하여 구현
  var drag: some Gesture {
    DragGesture()
      .onChanged { gesture in
        draggedOffset = accumulatedOffset + gesture.translation
      }
      .onEnded { gesture in
        accumulatedOffset = accumulatedOffset + gesture.translation
      }
  }
  
extension CGSize {
  static func + (lhs: Self, rhs: Self) -> Self {
    CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
  }
}
  • 전체 코드
import SwiftUI
import Combine

struct ContentView: View {
  @State private var draggedOffset = CGSize.zero
  @State private var accumulatedOffset = CGSize.zero
  
  var body: some View {
    Circle()
      .foregroundColor(Color.blue)
      .frame(width: 100, height: 100)
      .offset(draggedOffset)
      .gesture(drag)
  }
  
  var drag: some Gesture {
    DragGesture()
      .onChanged { gesture in
        draggedOffset = accumulatedOffset + gesture.translation
      }
      .onEnded { gesture in
        accumulatedOffset = accumulatedOffset + gesture.translation
      }
  }
}

extension CGSize {
  static func + (lhs: Self, rhs: Self) -> Self {
    CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
  }
}

* 참고

https://developer.apple.com/documentation/swiftui/draggesture

Comments