Skip to content

Commit

Permalink
Dynamically added segments crash fix (#6)
Browse files Browse the repository at this point in the history
* removed odd tests

* fixed crash when dynamically adding segments
  • Loading branch information
KazaiMazai authored Jun 15, 2024
1 parent c3c6396 commit 309f7d3
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 40 deletions.
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.

0 comments on commit 309f7d3

Please sign in to comment.