Last active
May 8, 2020 21:48
-
-
Save pato/7527c7e1de465758eaa138b8d406af1a to your computer and use it in GitHub Desktop.
Creating a TabView that responds to horizontal swipe gestures to change tabs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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