Skip to content

Instantly share code, notes, and snippets.

@pato
Last active May 8, 2020 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pato/7527c7e1de465758eaa138b8d406af1a to your computer and use it in GitHub Desktop.
Save pato/7527c7e1de465758eaa138b8d406af1a to your computer and use it in GitHub Desktop.
Creating a TabView that responds to horizontal swipe gestures to change tabs
//
// ContentView.swift
// SwipeableTabView
//
// Created by Patricio Lankenau on 5/8/20.
// This is free and unencumbered software released into the public domain.
//
import SwiftUI
struct ContentView: View {
@State private var selectedTab = 0
let numTabs = 2
let minDragTranslationForSwipe: CGFloat = 50
var body: some View {
TabView(selection: $selectedTab){
NavigationView{
Text("Hello, World!")
}.tabItem {
Image(systemName: "house")
Text("Home")
}.tag(0)
.highPriorityGesture(DragGesture().onEnded({
self.handleSwipe(translation: $0.translation.width)
}))
NavigationView{
Text("Salut, tout le monde!")
}.tabItem {
Image(systemName: "timelapse")
Text("Space")
}.tag(1)
.highPriorityGesture(DragGesture().onEnded({
self.handleSwipe(translation: $0.translation.width)
}))
}
}
private func handleSwipe(translation: CGFloat) {
if translation > minDragTranslationForSwipe && selectedTab > 0 {
selectedTab -= 1
} else if translation < -minDragTranslationForSwipe && selectedTab < numTabs-1 {
selectedTab += 1
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment