Tab bar / navigation selection
Switching tabs in a custom tab bar gives a subtle tick per change.
import SwiftUI
struct CustomTabBar: View {
@Binding var selected: Int
let icons = ["house", "magnifyingglass", "bell", "person"]
var body: some View {
HStack {
ForEach(icons.indices, id: \.self) { i in
Button { selected = i } label: {
Image(systemName: icons[i])
.font(.title3)
.foregroundStyle(selected == i ? .primary : .tertiary)
.frame(maxWidth: .infinity)
}
}
}
.padding(.vertical, 12)
.background(.bar)
// Fires only when `selected` changes — repeat taps on the
// same tab stay silent, which is the correct behavior.
.sensoryFeedback(.selection, trigger: selected)
}
} final class TabBarController: UITabBarController, UITabBarControllerDelegate {
private let haptic = UISelectionFeedbackGenerator()
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
func tabBarController(_ tbc: UITabBarController,
didSelect viewController: UIViewController) {
haptic.selectionChanged()
}
}