From 91ced04b699e5c73315cdb0f0a0d3b62bb678fb8 Mon Sep 17 00:00:00 2001 From: Nicolas Frugoni Date: Mon, 15 Apr 2024 16:15:11 +0100 Subject: [PATCH] Refactor BPKHorizontalNavigation to include onClick handlers for tab selection --- .../Classes/BPKHorizontalNavigation.swift | 64 +++++++++++-------- .../HorizontalNavigation/README.md | 24 +++---- .../BPKHorizontalNavigationTests.swift | 16 +++-- .../HorizontalNavigationExampleView.swift | 37 +++++------ 4 files changed, 79 insertions(+), 62 deletions(-) diff --git a/Backpack-SwiftUI/HorizontalNavigation/Classes/BPKHorizontalNavigation.swift b/Backpack-SwiftUI/HorizontalNavigation/Classes/BPKHorizontalNavigation.swift index 294556b80..562713c6a 100644 --- a/Backpack-SwiftUI/HorizontalNavigation/Classes/BPKHorizontalNavigation.swift +++ b/Backpack-SwiftUI/HorizontalNavigation/Classes/BPKHorizontalNavigation.swift @@ -41,10 +41,16 @@ public extension BPKHorizontalNavigation { struct Tab { let title: String let icon: BPKIcon? - - public init(title: String, icon: BPKIcon? = nil) { + let onClick: () -> Void + + public init( + title: String, + icon: BPKIcon? = nil, + onClick: @escaping () -> Void + ) { self.title = title self.icon = icon + self.onClick = onClick } } } @@ -52,25 +58,26 @@ public extension BPKHorizontalNavigation { public struct BPKHorizontalNavigation: View { let tabs: [Tab] let size: Size - @Binding var selectedTab: Int + let selectedTab: Int - public init(tabs: [Tab], size: Size = .default, selectedTab: Binding) { + public init( + tabs: [Tab], + size: Size = .default, + selectedTab: Int + ) { self.tabs = tabs self.size = size - _selectedTab = selectedTab + self.selectedTab = selectedTab } public var body: some View { ZStack(alignment: .bottom) { HStack(spacing: BPKSpacing.none) { ForEach(0.. some View { + VStack { BPKHorizontalNavigation( tabs: [ - .init(title: "One", icon: .flight), - .init(title: "Two", icon: .flight), - .init(title: "Three", icon: .flight) + .init(title: "One", onClick: { selectedTab = 0 }), + .init(title: "Two", onClick: { selectedTab = 1 }), + .init(title: "Three", onClick: { selectedTab = 2 }) ], - selectedTab: $selectedTab - ) - BPKHorizontalNavigation( - tabs: [.init(title: "One"), .init(title: "Two"), .init(title: "Three")], - size: .small, - selectedTab: $selectedTab + size: size, + selectedTab: selectedTab ) BPKHorizontalNavigation( tabs: [ - .init(title: "One", icon: .flight), - .init(title: "Two", icon: .flight), - .init(title: "Three", icon: .flight) + .init(title: "One", icon: .flight, onClick: { selectedTab = 0 }), + .init(title: "Two", icon: .flight, onClick: { selectedTab = 1 }), + .init(title: "Three", icon: .flight, onClick: { selectedTab = 2 }) ], - size: .small, - selectedTab: $selectedTab + size: size, + selectedTab: selectedTab ) } }