I was playing around with the brand-new reorderable API and couldn't get it to work within previews. Is there a specific way to get previews to work with reorderable, or do I need to compile every time? I was also curious if there will be an addition to the Array generic struct, as it seems like the solution there currently is is just an extension, although the way it's being promoted makes it seem like it is built into the type.
Reorderable with Xcode previews
Hi,
Thanks for trying out previews with the new reorderable APIs. Would you be able to provide a code snippet of what you've tried?
Hi, thanks for getting back
Here is a code snippet where this issue will occur:
import SwiftUI
struct TestItem: Identifiable {
let id = UUID()
let color: Color
}
struct POSView: View {
@State private var items = [
TestItem(color: .orange),
TestItem(color: .purple),
TestItem(color: .teal),
TestItem(color: .blue),
TestItem(color: .pink),
TestItem(color: .green)
]
let columns = [GridItem(.adaptive(minimum: 100))]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 16) {
ForEach(items) { item in
RoundedRectangle(cornerRadius: 15)
.fill(item.color.gradient)
.frame(width: 100, height: 100)
}
.reorderable()
}
.reorderContainer(for: TestItem.self) { difference in
items.apply(difference: difference)
}
.padding()
}
}
}
extension Array {
mutating func apply<CollectionID: Hashable & Sendable>(
difference: ReorderDifference<Element.ID, CollectionID>
) where Element: Identifiable, Element.ID: Sendable {
guard let sourceIndex = firstIndex(where: { $0.id == difference.sources[0] }) else { return }
let movedCard = remove(at: sourceIndex)
var destination: Int
switch difference.destination.position {
case let .before(value):
guard let index = firstIndex(where: { $0.id == value })
else { return }
destination = index
case .end:
destination = endIndex
}
insert(movedCard, at: destination)
}
}
#Preview {
POSView()
}
Again, thanks for looking this over. It would help improve development experience and speeds if there were an intuitive way to use these APIs with Xcode previews. I also feel like there should be a shorter holding time before an item can be dragged as it does feel awfully long on real hardware, maybe just a matter of my own opinion though. (Testing on iPhone 16)