element-ios/RiotSwiftUI/Modules/Room/PollHistory/View/SegmentedPicker.swift

73 lines
2.4 KiB
Swift
Raw Normal View History

2023-01-12 14:45:16 +00:00
//
// Copyright 2023 New Vector Ltd
//
// 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
2023-01-13 15:38:29 +00:00
struct SegmentedPicker<Segment: Hashable & CustomStringConvertible>: View {
private let segments: [Segment]
private let selection: Binding<Segment>
2023-01-12 14:45:16 +00:00
private let interSegmentSpacing: CGFloat
@Environment(\.theme) private var theme
2023-01-13 15:38:29 +00:00
init(segments: [Segment], selection: Binding<Segment>, interSegmentSpacing: CGFloat) {
2023-01-12 14:45:16 +00:00
self.segments = segments
self.selection = selection
self.interSegmentSpacing = interSegmentSpacing
}
var body: some View {
HStack(spacing: interSegmentSpacing) {
2023-01-13 15:38:29 +00:00
ForEach(segments, id: \.hashValue) { segment in
let isSelectedSegment = segment == selection.wrappedValue
2023-01-12 14:45:16 +00:00
Button {
2023-01-13 15:38:29 +00:00
selection.wrappedValue = segment
2023-01-12 14:45:16 +00:00
} label: {
2023-01-13 15:38:29 +00:00
Text(segment.description)
2023-01-12 14:45:16 +00:00
.font(isSelectedSegment ? theme.fonts.headline : theme.fonts.body)
.underline(isSelectedSegment)
}
.accentColor(isSelectedSegment ? theme.colors.accent : theme.colors.primaryContent)
2023-01-16 11:01:24 +00:00
.accessibilityLabel(segment.description)
.accessibilityValue(isSelectedSegment ? VectorL10n.accessibilitySelected : "")
2023-01-12 14:45:16 +00:00
}
}
}
}
struct SegmentedPicker_Previews: PreviewProvider {
static var previews: some View {
SegmentedPicker(
segments: [
2023-01-13 15:38:29 +00:00
"Segment 1",
"Segment 2"
2023-01-12 14:45:16 +00:00
],
2023-01-13 15:38:29 +00:00
selection: .constant("Segment 1"),
interSegmentSpacing: 14
)
SegmentedPicker(
segments: [
"Segment 1",
"Segment 2"
],
selection: .constant("Segment 2"),
2023-01-12 14:45:16 +00:00
interSegmentSpacing: 14
)
}
}