article

Thursday, August 26, 2021

SwiftUI Swipe Menu - Drag Gesture

SwiftUI Swipe Menu - Drag Gesture

In this tutorial I'm going to show how to use drag gesture swipe up-down menu with animations

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var size : CGFloat = UIScreen.main.bounds.height - 140
    
    var body: some View {
        
        ZStack{
            Text("Hello Cairocoders")
                .fontWeight(.heavy)
                .foregroundColor(Color.white)
                
            swipe().cornerRadius(20).padding(15).offset(y: size)
            .gesture(DragGesture()
                .onChanged({ (value) in
                    
                    if value.translation.height > 0{
                        self.size = value.translation.height
                    }
                    else{
                        let temp = UIScreen.main.bounds.height - 140
                        self.size = temp + value.translation.height
                    }
                })
                .onEnded({ (value) in
                    if value.translation.height > 0{
                        if value.translation.height > 200{
                            self.size = UIScreen.main.bounds.height - 140
                        }
                        else{
                            self.size = 15
                        }
                    }
                    else{
                        //since in negative lower value will be greater...
                        if value.translation.height < -200{
                            self.size = 15
                        }
                        else{
                            self.size = UIScreen.main.bounds.height - 140
                        }
                    }
                })).animation(.spring())
            // animation for drag
        }
        .background(Color.gray.edgesIgnoringSafeArea(.all))
    }
}

struct swipe : View {
    
    let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
    
    var body : some View{
        VStack{
            VStack{
                Text("Swipe up to See More").fontWeight(.heavy).padding([.top,.bottom],15)
            }
            // your custom view here....
            HStack {
                NavigationView {
                    List {
                        ForEach(countryList, id: \.self) { country in
                           Text(country)
                        }
                    }
                    .navigationTitle("Country")
                }
            }
        }.background(Color.white)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post