Skip to content

Commit

Permalink
Merge pull request #2141 from Skyscanner/donburi/DON-1029-segmented-c…
Browse files Browse the repository at this point in the history
…ontrol-custom

DON-1029 segmented control custom
  • Loading branch information
maxgirt authored Jan 29, 2025
2 parents f87cbb7 + 387bcd2 commit a254a04
Show file tree
Hide file tree
Showing 13 changed files with 317 additions and 18 deletions.
133 changes: 133 additions & 0 deletions Backpack-SwiftUI/SegmentedControl/Classes/BPKSegmentedControl.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright © 2025 Skyscanner Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import SwiftUI
/// A linear set of mutually exclusive buttons.
///
/// You create a segmented control by providing a list of `items` that will serve as the segments' titles
/// and a `selectedIndex` binding. Bind `selectedIndex`
/// to an Int property that determines which segment is selected.
/// The colours can be customised using the`style` parameter.
public struct BPKSegmentedControl: View {
private var items: [String]
private var accessibilityLabel: String
@Binding private var selectedIndex: Int
private let style: Style
private let segmentHeight: CGFloat = 32
@Namespace var namespace

/// Creates a Segment Control that generates its labels from a list of Strings
///
/// - Parameters:
/// - items: An Array of Strings that describes the purpose of each segment. Limited to 4 items.
/// - selectedIndex: A binding to an Int that indicates which segment is selected
/// - accessibilityLabel: A string used to identify the component and each segment
/// - style: A style defining the customised colours of the component
public init(
items: [String],
selectedIndex: Binding<Int>,
accessibilityLabel: String,
style: Style = .defaultStyle
) {
// Limit the number of items to 4
self.items = Array(items.prefix(4))
self.accessibilityLabel = accessibilityLabel
self.style = style
_selectedIndex = selectedIndex
}

public var body: some View {
ZStack {
HStack(spacing: 0) {
ForEach(items.indices, id: \.self) { index in
segmentButton(for: index)
.matchedGeometryEffect(id: index, in: namespace, isSource: true)
}
}
.background {
Rectangle()
.fill(Color(style.selectedBgColor))
.matchedGeometryEffect(id: selectedIndex, in: namespace, isSource: false)
}
.background(Color(style.bgColor))
.animation(.spring(duration: 0.25), value: selectedIndex)
.cornerRadius(8)
.padding()
.accessibilityIdentifier(accessibilityLabel)
.frame(height: segmentHeight)
}
}

@ViewBuilder
private func segmentButton(for index: Int) -> some View {
HStack(spacing: 0) {
Button(
action: { withAnimation { selectedIndex = index } },
label: {
Text(items[index])
.font(style: .label2)
.frame(maxWidth: .infinity, minHeight: segmentHeight)
.foregroundColor(selectedIndex == index ? style.selectedTextColor : style.textColor)
.accessibilityIdentifier("\(accessibilityLabel)_\(index)")
.accessibilityAddTraits(selectedIndex == index ? .isSelected : [])
.sizeCategory(.large)

}
)
.frame(maxHeight: .infinity)

if index < items.count - 1 && selectedIndex != index && selectedIndex != index + 1 {
separator
}
}
}

private var separator: some View {
Rectangle()
.fill(Color(.lineColor))
.frame(width: 1, height: segmentHeight)
}

public struct Style {
let bgColor: BPKColor
let textColor: BPKColor
let selectedBgColor: BPKColor
let selectedTextColor: BPKColor

public init(bgColor: BPKColor, textColor: BPKColor, selectedBgColor: BPKColor, selectedTextColor: BPKColor) {
self.bgColor = bgColor
self.textColor = textColor
self.selectedBgColor = selectedBgColor
self.selectedTextColor = selectedTextColor
}
}
}

// MARK: - Default component style
public extension BPKSegmentedControl.Style {
static let defaultStyle = Self(
bgColor: .segmentedControlCanvasDefaultColor,
textColor: .textPrimaryColor,
selectedBgColor: .corePrimaryColor,
selectedTextColor: .textOnDarkColor
)
}

#Preview {
BPKSegmentedControl(items: ["1", "2", "3", "4"], selectedIndex: .constant(3), accessibilityLabel: "example_label")
}
50 changes: 50 additions & 0 deletions Backpack-SwiftUI/SegmentedControl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Backpack-SwiftUI/SegmentedControl

[![Cocoapods](https://img.shields.io/cocoapods/v/Backpack-SwiftUI.svg?style=flat)](hhttps://cocoapods.org/pods/Backpack-SwiftUI)
[![class reference](https://img.shields.io/badge/Class%20reference-iOS-blue)](https://backpack.github.io/ios/versions/latest/swiftui/Structs/BPKSegmentedControl.html)
[![view on Github](https://img.shields.io/badge/Source%20code-GitHub-lightgrey)](https://github.com/Skyscanner/backpack-ios/tree/main/Backpack-SwiftUI/SegmentedControl)

## Default

| Day | Night |
| --- | --- |
| <img src="https://raw.githubusercontent.com/Skyscanner/backpack-ios/main/screenshots/iPhone-swiftui_segmented-control___default_lm.png" alt="" width="375" /> |<img src="https://raw.githubusercontent.com/Skyscanner/backpack-ios/main/screenshots/iPhone-swiftui_segmented-control___default_dm.png" alt="" width="375" /> |

## Usage

Use an array of strings to set the texts shown by the segmented control as a `BPKText` label.
The colours can be customised using the`style` parameter.

### Default style

```swift
import Backpack_SwiftUI
@State var selectedIndex = 0
private let accessibilityLabel = "bpk_segmented_control_example"
private let items: [String] = ["1", "2", "3"]

BPKSegmentedControl(
items: items,
selectedIndex: $selectedIndex,
accessibilityLabel: accessibilityLabel,
style: .defaultStyle
)
```

### Custom style

```swift
import Backpack_SwiftUI
@State var selectedIndex = 0
private let accessibilityLabel = "bpk_segmented_control_example"
private let items: [String] = ["1", "2", "3"]

BPKSegmentedControl(
items: items,
selectedIndex: $selectedIndex,
accessibilityLabel: accessibilityLabel,
style: .init(
bgColor: .black, textColor: .white, selectedBgColor: .white, selectedTextColor: .black
)
)
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright © 2025 Skyscanner Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import XCTest
import SwiftUI
@testable import Backpack_SwiftUI

class BPKSegmentedControlTests: XCTestCase {
func test_firstSegmentSelected() {
assertSnapshot(
BPKSegmentedControl(
items: ["One", "Two", "Three"],
selectedIndex: .constant(0),
accessibilityLabel: "bpk_segmented_control_example",
style: .defaultStyle)
.frame(width: 200)
)
}

func test_accessibility() {
let segmentedControl = BPKSegmentedControl(
items: ["One", "Two", "Three"],
selectedIndex: .constant(0),
accessibilityLabel: "bpk_segmented_control_example"
)
.frame(width: 200)
assertA11ySnapshot(segmentedControl)
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions Example/Backpack Screenshot/SwiftUIScreenshots.swift
Original file line number Diff line number Diff line change
Expand Up @@ -850,5 +850,11 @@ class SwiftUIScreenshots: BackpackSnapshotTestCase {
saveScreenshot(component: "card-button", scenario: "all", userInterfaceStyle: userInterfaceStyle)
tapBackButton()
}

await navigate(title: "Segmented Control") {
switchTab(title: "SwiftUI")
saveScreenshot(component: "segmented-control", scenario: "default", userInterfaceStyle: userInterfaceStyle)
tapBackButton()
}
}
}
32 changes: 14 additions & 18 deletions Example/Backpack.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
53C6622929EA0DAB00BF1A62 /* AttributedTextExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53C6620F29EA0DAB00BF1A62 /* AttributedTextExampleView.swift */; };
53C7F0B92A4C615D003A8740 /* ChipGroupSingleSelectRailExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53C7F0B52A4C615D003A8740 /* ChipGroupSingleSelectRailExampleView.swift */; };
53C7F0BA2A4C615D003A8740 /* ChipGroupSingleSelectWrapExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53C7F0B62A4C615D003A8740 /* ChipGroupSingleSelectWrapExampleView.swift */; };
53D4614E29E574EB0061C222 /* BuildFile in Sources */ = {isa = PBXBuildFile; };
53D4614E29E574EB0061C222 /* (null) in Sources */ = {isa = PBXBuildFile; };
53D6396F2A7D46ED007EF376 /* MapMarkerExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53D6396E2A7D46ED007EF376 /* MapMarkerExampleView.swift */; };
53D7FBB527F715AF00DEE588 /* UIWindowFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53D7FBB427F715AF00DEE588 /* UIWindowFactory.swift */; };
53E075A527FC780C0033147C /* NavBarGroups.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53E075A427FC780C0033147C /* NavBarGroups.swift */; };
Expand Down Expand Up @@ -218,6 +218,7 @@
E397BEA222F5F59000C8EC04 /* BottomSheetScrollableContentViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E397BEA122F5F59000C8EC04 /* BottomSheetScrollableContentViewController.swift */; };
E397BEA422F5FCE500C8EC04 /* BottomSheetBottomSectionVIewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E397BEA322F5FCE500C8EC04 /* BottomSheetBottomSectionVIewController.swift */; };
E397BEA622F5FFDD00C8EC04 /* Storyboards.swift in Sources */ = {isa = PBXBuildFile; fileRef = E397BEA522F5FFDD00C8EC04 /* Storyboards.swift */; };
EED519BF2D3EBD8300F898D7 /* SegmentedControlExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EED519BD2D3EBD8300F898D7 /* SegmentedControlExampleView.swift */; };
F00CA3D9299D53450027ACE7 /* FloatingNotificationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F00CA3D8299D53450027ACE7 /* FloatingNotificationViewController.swift */; };
F00F15692993F24700213F0D /* CarouselViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F00F15682993F24700213F0D /* CarouselViewController.swift */; };
/* End PBXBuildFile section */
Expand Down Expand Up @@ -473,6 +474,7 @@
E397BEA322F5FCE500C8EC04 /* BottomSheetBottomSectionVIewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BottomSheetBottomSectionVIewController.swift; sourceTree = "<group>"; };
E397BEA522F5FFDD00C8EC04 /* Storyboards.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Storyboards.swift; sourceTree = "<group>"; };
EDBC7CA36756032862B5D581 /* Pods_Backpack_Native.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Backpack_Native.framework; sourceTree = BUILT_PRODUCTS_DIR; };
EED519BD2D3EBD8300F898D7 /* SegmentedControlExampleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SegmentedControlExampleView.swift; sourceTree = "<group>"; };
F00CA3D8299D53450027ACE7 /* FloatingNotificationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FloatingNotificationViewController.swift; sourceTree = "<group>"; };
F00F15682993F24700213F0D /* CarouselViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CarouselViewController.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
Expand Down Expand Up @@ -1043,6 +1045,7 @@
793EC5502836139A00D627F6 /* Components */ = {
isa = PBXGroup;
children = (
EED519BE2D3EBD8300F898D7 /* SegmentedControl */,
25006AAE2C60B15D0038D7CA /* SearchControlInput */,
DB0A8DA62C57F507003DC186 /* CardCarousel */,
13E8849B2C53A0A400A3138D /* BannerAlert */,
Expand Down Expand Up @@ -1621,6 +1624,14 @@
path = "Bottom Sheet";
sourceTree = "<group>";
};
EED519BE2D3EBD8300F898D7 /* SegmentedControl */ = {
isa = PBXGroup;
children = (
EED519BD2D3EBD8300F898D7 /* SegmentedControlExampleView.swift */,
);
path = SegmentedControl;
sourceTree = "<group>";
};
F00CA3D7299D532E0027ACE7 /* FloatingNotification */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -1650,7 +1661,6 @@
6003F588195388D20070C39A /* Resources */,
84EFE62BE1534CD46CAFBDBF /* [CP] Embed Pods Frameworks */,
D68AF8FA2174CB9C00BA743D /* Run Script */,
5059D4BC2567A5EB643578E0 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
Expand Down Expand Up @@ -1807,21 +1817,6 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
5059D4BC2567A5EB643578E0 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Backpack-Native/Pods-Backpack-Native-resources.sh\"\n";
showEnvVarsInLog = 0;
};
84EFE62BE1534CD46CAFBDBF /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
Expand Down Expand Up @@ -1957,7 +1952,7 @@
5390DB612909940700F0F790 /* ColorTokensViewController.swift in Sources */,
794E1FF8280CF63100B965FF /* RadiusTokensView.swift in Sources */,
53B6DB6A27FC73A90042B7C0 /* LabelGroups.swift in Sources */,
53D4614E29E574EB0061C222 /* BuildFile in Sources */,
53D4614E29E574EB0061C222 /* (null) in Sources */,
53C6621329EA0DAB00BF1A62 /* SpinnerExampleView.swift in Sources */,
53BAC3F12A71415800236CC9 /* SectionHeaderGroups.swift in Sources */,
53C6622429EA0DAB00BF1A62 /* ButtonsPlaygroundView.swift in Sources */,
Expand All @@ -1979,6 +1974,7 @@
D2EB964C25C05DF600988978 /* MapViewController.swift in Sources */,
D211A90C22D8B42B00447B64 /* HorizontalNavViewController.swift in Sources */,
53D6396F2A7D46ED007EF376 /* MapMarkerExampleView.swift in Sources */,
EED519BF2D3EBD8300F898D7 /* SegmentedControlExampleView.swift in Sources */,
BA809EC82B05FC2E0030D1E7 /* AppSearchModalGroups.swift in Sources */,
53C7F0BA2A4C615D003A8740 /* ChipGroupSingleSelectWrapExampleView.swift in Sources */,
1318F74E2C77734C00D42847 /* FieldSetExampleView.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright © 2025 Skyscanner Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import SwiftUI
import Backpack_SwiftUI

struct SegmentedControlExampleView: View {
@State var selectedIndex = 0
private let accessibilityLabel = "bpk_segmented_control_example"
private let items: [String] = ["1", "2", "3", "4"]
private let longerItems: [String] = ["Item 1", "Item 2", "Very long item 3", "Item 4"]

var body: some View {
VStack(spacing: 10) {
Text("Default style")

BPKSegmentedControl(
items: longerItems,
selectedIndex: $selectedIndex,
accessibilityLabel: accessibilityLabel,
style: .defaultStyle
)

Text("Custom style")
BPKSegmentedControl(
items: items,
selectedIndex: $selectedIndex,
accessibilityLabel: accessibilityLabel,
style: .init(
bgColor: .black, textColor: .white, selectedBgColor: .white, selectedTextColor: .black
)
)

Text("Selected index: \(selectedIndex)")
}
}
}

#Preview {
SegmentedControlExampleView()
}
Loading

0 comments on commit a254a04

Please sign in to comment.