Skip to content

Instantly share code, notes, and snippets.

@eegrok
Created February 23, 2023 21:39
Show Gist options
  • Save eegrok/9ccfcf060aab1e065651d0e2f70fd46c to your computer and use it in GitHub Desktop.
Save eegrok/9ccfcf060aab1e065651d0e2f70fd46c to your computer and use it in GitHub Desktop.
Example of how to tell when a TabView changes which tab is selected, or when the same tab is tapped when it is already selected.
//
// ContentView.swift
// TestTabs
//
// Created by Kem Mason on 24/02/23.
//
import SwiftUI
enum TopNavTag: Hashable {
case tab1, tab2
}
struct Tab1: View {
var body: some View {
Text("Tab1")
}
}
struct Tab2: View {
var body: some View {
Text("Tab2")
}
}
/* method 1
extension Binding {
// long name primaril
func onUpdatedValue(_ closure: @escaping () -> Void) -> Binding<Value> {
Binding(get: {
wrappedValue
}, set: { newValue in
wrappedValue = newValue
closure()
})
}}
struct ContentView: View {
@State var previouslySelectedTab = TopNavTag.tab1
@State var selectedTab: TopNavTag = .tab1
var body: some View {
TabView(selection: $selectedTab.onUpdatedValue {
if (previouslySelectedTab != selectedTab) {
previouslySelectedTab = selectedTab
print("new tab selected: \(selectedTab)")
} else {
print("current tab selected again: \(selectedTab)")
}
})
{
Tab1().tabItem {
Label("Tab1", systemImage: "star")
}.tag(TopNavTag.tab1)
Tab2().tabItem {
Label("Tab2", systemImage: "chart.bar")
}.tag(TopNavTag.tab2)
}
}
}
*/
// method 2
struct ContentView: View {
@State var previouslySelectedTab = TopNavTag.tab1
@State var selectedTab: TopNavTag = .tab1
private var selection: Binding<TopNavTag> { Binding(
get: { selectedTab },
set: { newValue in
selectedTab = newValue
if newValue == previouslySelectedTab {
print("selected again: \(newValue)")
} else {
previouslySelectedTab = newValue
print("selected first time: \(newValue)")
}
}
)}
var body: some View {
TabView(selection: selection)
{
Tab1().tabItem {
Label("Tab1", systemImage: "star")
}.tag(TopNavTag.tab1)
Tab2().tabItem {
Label("Tab2", systemImage: "chart.bar")
}.tag(TopNavTag.tab2)
}
}
}
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