How to use DragGesture to move, drag, swipe in SwiftUI | Continued Learning #4
move
, drag
, swipe
하는 데 사용되는 제스처. 커스텀 모달 뷰를 구현하거나 카드 뷰 스와이프를 할 때에도 사용되는 것 같다.offset
으로 변경한다.scalEffect
, rotationEffect
는 각각 확대/축소의 크기, 회전 효과를 주자. .offset(currentOffset)
.scaleEffect(currentScaleAmount)
.rotationEffect(currentRotationAngle)
.gesture(
DragGesture()
.onChanged({ value in
withAnimation(.spring()) {
currentOffset = value.translation
}
})
.onEnded({ value in
withAnimation(.spring()) {
currentOffset = .zero
}
})
)
import SwiftUI
// DRAG GESTURE -> MAKE IT SWIPABLE USING DRAG GESTURE
struct DragGestureBootCamp: View {
@State private var currentOffset: CGSize = .zero
var currentScaleAmount: CGFloat {
let max = UIScreen.main.bounds.width / 2
let currentAmount = abs(currentOffset.width)
let percentage = currentAmount / max
return 1.0 - min(percentage, 0.5) * 0.5
}
var currentRotationAngle: Angle {
let max = UIScreen.main.bounds.width / 2
let currentAmount = currentOffset.width
let percentage = currentAmount / max
let percentageAsDouble = Double(percentage)
let maxAngle = 10.0
return Angle(degrees: percentageAsDouble * maxAngle)
}
var body: some View {
ZStack {
VStack {
Text("\(currentOffset.width)")
Spacer()
}
RoundedRectangle(cornerRadius: 20)
.frame(width: 300, height: 500)
.offset(currentOffset)
.scaleEffect(currentScaleAmount)
.rotationEffect(currentRotationAngle)
.gesture(
DragGesture()
.onChanged({ value in
withAnimation(.spring()) {
currentOffset = value.translation
}
})
.onEnded({ value in
withAnimation(.spring()) {
currentOffset = .zero
}
})
)
}
}
}
.onEnded({ value in
withAnimation(.spring()) {
if currentDragOffsetY < -150 {
endingOffsetY = -startingOffsetY
currentDragOffsetY = .zero
} else if endingOffsetY != 0 && currentDragOffsetY > 150 {
endingOffsetY = .zero
currentDragOffsetY = .zero
} else {
currentDragOffsetY = .zero
}
}
})
import SwiftUI
struct DragGestureBootCamp2: View {
@State private var startingOffsetY: CGFloat = UIScreen.main.bounds.height * 0.85
@State private var currentDragOffsetY: CGFloat = 0
@State private var endingOffsetY: CGFloat = 0
var body: some View {
ZStack {
Color.green.ignoresSafeArea()
MySignUpView()
.offset(y: startingOffsetY)
.offset(y: currentDragOffsetY)
.offset(y: endingOffsetY)
.gesture(
DragGesture()
.onChanged({ value in
withAnimation(.spring()) {
currentDragOffsetY = value.translation.height
}
})
.onEnded({ value in
withAnimation(.spring()) {
if currentDragOffsetY < -150 {
endingOffsetY = -startingOffsetY
currentDragOffsetY = .zero
} else if endingOffsetY != 0 && currentDragOffsetY > 150 {
endingOffsetY = .zero
currentDragOffsetY = .zero
} else {
currentDragOffsetY = .zero
}
}
})
)
// Text("\(currentDragOffsetY)")
}
.ignoresSafeArea(edges: .bottom)
}
}