1. DragGesture 拖动手势操作
1.1 实现
/// 拖动手势
struct DragGestureBootcamp: View {
@State var offset: CGSize = .zero
var body: some View {
//dragGesture1
dragGesture2
}
/// 方式二
var dragGesture2: some View{
ZStack {
VStack {
Text("\(offset.width)")
Spacer()
}
RoundedRectangle(cornerRadius: 20)
.frame(width: 300, height: 500)
.offset(offset)
.scaleEffect(getScaleAmount())
.rotationEffect(Angle(degrees: getRotationAmount()))
.gesture(
DragGesture()
.onChanged{ value in
withAnimation(.spring()){
offset = value.translation
}
}
.onEnded{ value in
withAnimation(.spring()){
offset = .zero
}
}
)
}
}
/// 获取缩放因子
func getScaleAmount() -> CGFloat{
// 最大值
let max = UIScreen.main.bounds.width / 2
// 当前数值
let currentAmount = abs(offset.width)
// 百分比
let percentage = currentAmount / max
return 1.0 - min(percentage, 0.5) * 0.5
}
/// 获取旋转因子
func getRotationAmount() -> Double{
// 最大值
let max = UIScreen.main.bounds.width / 2
// 当前数值
let currentAmount = offset.width
// 百分比
let percentage = currentAmount / max
// 转换 Double
let percentageAsDouble = Double(percentage)
// 最大角度
let maxAngle: Double = 10
return percentageAsDouble * maxAngle
}
/// 方式一
var dragGesture1: some View{
RoundedRectangle(cornerRadius: 20)
.frame(width: 100, height: 100)
.offset(offset)
.gesture(
DragGesture()
.onChanged{ value in
withAnimation(.spring()){
offset = value.translation
}
}
.onEnded{ value in
withAnimation(.spring()){
offset = .zero
}
}
)
}
}
1.2 效果图:
2. DragGesture 拖动手势2操作
2.1 实现
/// 拖动手势2
struct DragGestureBootcamp2: View {
@State var startingOffsetY: CGFloat = UIScreen.main.bounds.height * 0.85
@State var currentDragOffsetY: CGFloat = 0
@State var endingOffsetY: CGFloat = 0
var body: some View {
ZStack{
Color.orange.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
} else if endingOffsetY != 0 && currentDragOffsetY > 150{
endingOffsetY = 0
}
currentDragOffsetY = 0
}
})
Text("\(currentDragOffsetY)")
}
.ignoresSafeArea(edges: .bottom)
}
}
struct MySignUpView: View {
var body: some View {
VStack(spacing: 20){
Image(systemName: "chevron.up")
.padding(.top)
Text("Sign up")
.font(.headline)
.fontWeight(.semibold)
Image(systemName: "flame.fill")
.resizable()
.scaledToFit()
.frame(width: 100, height: 100)
Text("This is the decription for our app. This is my favorite SwiftUI course and I recommend to all of my friends to subscribe to Swiftful Thinking!")
.multilineTextAlignment(.center)
Text("Create an account")
.foregroundColor(.white)
.font(.headline)
.padding()
.padding(.horizontal)
.background(Color.black.cornerRadius(10))
Spacer()
}
.frame(maxWidth: .infinity)
.background(Color.white)
.cornerRadius(30)
}
}