Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically added segments crash fix #6

Merged
merged 2 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions Sources/SegmentedPicker/SegmentedPicker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ public struct SegmentedPicker<Element, Content, Selection>: View
where
Content: View,
Selection: View {

public typealias Data = [Element]

@State private var frames: [CGRect]
@State private var frames: [Data.Index: CGRect] = [:]
@Binding private var selectedIndex: Data.Index?

private let data: Data
Expand All @@ -32,19 +32,18 @@ public struct SegmentedPicker<Element, Content, Selection>: View
self.content = content
self.selection = selection
self._selectedIndex = selectedIndex
self._frames = State(wrappedValue: Array(repeating: .zero,
count: data.count))
self.selectionAlignment = selectionAlignment
}


public var body: some View {
ZStack(alignment: Alignment(horizontal: .horizontalCenterAlignment,
vertical: selectionAlignment)) {

if let selectedIndex = selectedIndex {
if let index = selectedIndex {
selection()
.frame(width: frames[selectedIndex].width,
height: frames[selectedIndex].height)
.frame(width: selectionFrame(at: index).width,
height: selectionFrame(at: index).height)
.alignmentGuide(.horizontalCenterAlignment) { dimensions in
dimensions[HorizontalAlignment.center]
}
Expand All @@ -57,7 +56,9 @@ public struct SegmentedPicker<Element, Content, Selection>: View
)
.buttonStyle(PlainButtonStyle())
.background(GeometryReader { proxy in
Color.clear.onAppear { frames[index] = proxy.frame(in: .global) }
Color.clear.onAppear {
frames[index] = proxy.frame(in: .global)
}
})
.alignmentGuide(.horizontalCenterAlignment,
isActive: selectedIndex == index) { dimensions in
Expand All @@ -67,4 +68,8 @@ public struct SegmentedPicker<Element, Content, Selection>: View
}
}
}

private func selectionFrame(at index: Data.Index) -> CGRect {
frames[index] ?? .zero
}
}
7 changes: 0 additions & 7 deletions Tests/LinuxMain.swift

This file was deleted.

15 changes: 0 additions & 15 deletions Tests/SegmentedPickerTests/SegmentedPickerTests.swift

This file was deleted.

9 changes: 0 additions & 9 deletions Tests/SegmentedPickerTests/XCTestManifests.swift

This file was deleted.