1. DragGesture 拖动手势操作
1.1 实现
/// 拖动手势
struct DragGestureBootcamp: View {@State var offset: CGSize = .zerovar body: some View {//dragGesture1dragGesture2}/// 方式二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 inwithAnimation(.spring()){offset = value.translation}}.onEnded{ value inwithAnimation(.spring()){offset = .zero}})}}/// 获取缩放因子func getScaleAmount() -> CGFloat{// 最大值let max = UIScreen.main.bounds.width / 2// 当前数值let currentAmount = abs(offset.width)// 百分比let percentage = currentAmount / maxreturn 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// 转换 Doublelet percentageAsDouble = Double(percentage)// 最大角度let maxAngle: Double = 10return percentageAsDouble * maxAngle}/// 方式一var dragGesture1: some View{RoundedRectangle(cornerRadius: 20).frame(width: 100, height: 100).offset(offset).gesture(DragGesture().onChanged{ value inwithAnimation(.spring()){offset = value.translation}}.onEnded{ value inwithAnimation(.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 = 0var 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 inwithAnimation(.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)}
}