Skip to content

Instantly share code, notes, and snippets.

@JEuler
Created March 16, 2025 23:31
Show Gist options
  • Save JEuler/cb4c31f715e3234fd03221fc96fb7bc7 to your computer and use it in GitHub Desktop.
Save JEuler/cb4c31f715e3234fd03221fc96fb7bc7 to your computer and use it in GitHub Desktop.
SwiftUI Reorder With Buttons List Example
import SwiftUI
// Simple example of a custom reordering implementation in SwiftUI
struct ReorderableListExample: View {
// Sample data
@State private var items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
@State private var isEditMode: EditMode = .inactive
var body: some View {
VStack {
// Toggle edit mode button
Button {
withAnimation {
isEditMode = isEditMode == .active ? .inactive : .active
}
} label: {
HStack {
Image(systemName: isEditMode == .active ? "checkmark" : "arrow.up.arrow.down")
Text(isEditMode == .active ? "Done" : "Reorder")
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(isEditMode == .active ? Color.green.opacity(0.2) : Color.blue.opacity(0.2))
.foregroundColor(isEditMode == .active ? .green : .blue)
.clipShape(Capsule())
}
// List content
if isEditMode == .active {
// Reorderable view with up/down buttons
VStack(spacing: 12) {
ForEach(0..<items.count, id: \.self) { index in
HStack {
Text(items[index])
.frame(maxWidth: .infinity, alignment: .leading)
// Up/down buttons
HStack(spacing: 12) {
Button {
moveItemUp(at: index)
} label: {
Image(systemName: "chevron.up")
.foregroundColor(.white)
.frame(width: 36, height: 36)
.background(index > 0 ? Color.blue : Color.gray.opacity(0.5))
.clipShape(Circle())
}
.disabled(index == 0)
Button {
moveItemDown(at: index)
} label: {
Image(systemName: "chevron.down")
.foregroundColor(.white)
.frame(width: 36, height: 36)
.background(index < items.count - 1 ? Color.blue : Color.gray.opacity(0.5))
.clipShape(Circle())
}
.disabled(index == items.count - 1)
}
}
.padding()
.background(Color(.secondarySystemBackground))
.cornerRadius(10)
}
}
} else {
// Regular list view
List {
ForEach(items, id: \.self) { item in
Text(item)
}
}
}
}
.padding()
.animation(.spring(response: 0.3, dampingFraction: 0.7), value: isEditMode)
}
// Move an item up in the list
private func moveItemUp(at index: Int) {
guard index > 0 else { return }
withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
items.swapAt(index, index - 1)
}
}
// Move an item down in the list
private func moveItemDown(at index: Int) {
guard index < items.count - 1 else { return }
withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
items.swapAt(index, index + 1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment