
Мне удалось начать перетаскивание из центра каждого круга и определить логику для onChanged и onEnded, но на данный момент я не могу получить путь для присоединения, некоторые помощь здесь была бы очень признательна, это моя собственная реализация ниже:
import SwiftUI
struct Line: Hashable {
var start: CGPoint
var end: CGPoint
func hash(into hasher: inout Hasher) {
hasher.combine(start.x)
hasher.combine(start.y)
hasher.combine(end.x)
hasher.combine(end.y)
}
static func ==(lhs: Line, rhs: Line) -> Bool {
return lhs.start == rhs.start && lhs.end == rhs.end
}
}
//collect circle positions
struct CirclePositionsKey: PreferenceKey {
static var defaultValue: [Int: CGPoint] { [:] }
static func reduce(value: inout [Int : CGPoint], nextValue: () -> [Int : CGPoint]) {
value.merge(nextValue(), uniquingKeysWith: { $1 })
}
}
struct LineDragGesture: View {
@State private var lines: [Line] = []
@State private var currentDragPoint: CGPoint? = nil
@State private var selectedCircleIndex: Int?
@State private var selectedCirclePosition: CGPoint?
@State private var correctPaths: [Int] = [0, 3, 6] // Correct path sequence
@State private var currentPathIndex: Int = 0
@State private var circlePositions: [Int: CGPoint] = [:]
@State private var correctCircleIndex = 0
@State private var correctCirclePosition: CGPoint = .zero
@State private var nextCorrectCircleIndex = 0
@State private var nextCorrectCirclePosition: CGPoint = .zero
var sortedCoordinates: [(key: Int, value: CGPoint)] {
circlePositions.sorted(by: { $0.key < $1.key})
}
let columns: [GridItem] = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
ZStack {
// Draw each completed line
ForEach(lines, id: \.self) { line in
Path { path in
path.move(to: line.start)
path.addLine(to: line.end)
}
.stroke(Color.black, lineWidth: 6)
}
// Draw the line from the chosen circle to the current drag point
if let currentDragPoint = currentDragPoint, let startingIndex = selectedCircleIndex {
Path { path in
path.move(to: circlePositions[startingIndex] ?? .zero)
path.addLine(to: currentDragPoint)
}
.stroke(Color.black, lineWidth: 6)
}
LazyVGrid(columns: columns, spacing: 20) {
ForEach(0..
Подробнее здесь: https://stackoverflow.com/questions/790 ... in-swiftui
Мобильная версия