DEV Community

GoyesDev
GoyesDev

Posted on

[SUI] Refreshable

Se pueden refrescar los datos de una lista (List) tirándola hacia abajo, lo que provoca que aparezca un indicador de carga encima para indicar dicha acción.

  • refreshable(action:): action es un closure asíncrono que se ejecuta cuando el usuario solicita una actualización.
struct ContentView: View {
  @State var contacts: [Contact] = [
    .init(name: "Luis"),
    .init(name: "David"),
    .init(name: "Goyes"),
    .init(name: "Garcés"),
  ]

  @State var selectedContacts: Set<Contact.ID> = []
  @State var editing: EditMode = .inactive

  var body: some View {
    NavigationStack {
      List(selection: $selectedContacts) {
        ForEach(contacts) { contact in
          Text(contact.name)
            .swipeActions {
              Button(role: .destructive) {
                contacts.removeAll { $0.id == contact.id }
              } label: {
                Image(systemName: "trash")
              }

              Button {
                print("Editando")
              } label: {
                Image(systemName: "pencil")
              }
              .tint(Color.yellow)
            }
        }
      }
      .refreshable {
        contacts = [
          .init(name: "Nuevo contacto 1"),
          .init(name: "Nuevo contacto 2"),
          .init(name: "Nuevo contacto 3"),
          .init(name: "Nuevo contacto 4"),
        ]
      }
      .environment(\.editMode, $editing)
      .deleteDisabled(false)
      .toolbar {
        Button {
          editing = (editing == .inactive) ? .active : .inactive
        } label: {
          Text(editing == .active ? "Listo" : "Editar")
        }

        Button {
          let indexes = selectedContacts.compactMap { id in
            contacts.firstIndex { $0.id == id }
          }.reduce(into: IndexSet()) { partialResult, index in
            partialResult.insert(index)
          }

          contacts.remove(atOffsets: indexes)
          selectedContacts = []
          editing = .inactive
        } label: {
          Label {
            Text("Eliminar")
          } icon: {
            Image(systemName: "trash")
          }
        }.disabled(selectedContacts.count == 0)
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)