Как создать SwipeActionsConfigurationForRowAt в представлении списка - SwiftUI (iOS 13)? - PullRequest
0 голосов
/ 20 февраля 2020

enter image description here

Я хочу создать представление списка в SwiftUI, где я могу показать две кнопки для различных действий, когда пользователь проведет пальцем влево. Я знаю, что есть опция для удаления (. OnDelete (выполнить: удалить)) , но я хочу добавить больше действий, как я упоминаю на изображении выше.

Я легко могу сделать это в UITalbleView с использованием Swift.

 func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    }

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

}

Но мой вопрос: Как я могу сделать это в SwiftUI, используя просмотр списка?

1 Ответ

0 голосов
/ 20 февраля 2020

Это быстрый код, который я набрал, но он дает простой пример того, как создать собственное решение UITableView:

    RoutineTableView(routines: routineDataSource.routines)
  .trailingSwipeActionsConfiguration {
    let editAction = UIContextualAction(
      style: .normal,
      title: "EDIT"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    editAction.backgroundColor = UIColor.darkGray
    let deleteAction = UIContextualAction(
      style: .destructive,
      title: "DELETE"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    let actions = [deleteAction, editAction]
    let configuration = UISwipeActionsConfiguration(actions: actions)
    return configuration
  }
  .onCellPress {
    print("hi there")
  }
  .navigationBarTitle("Routines")

и

private class CustomDataSource<SectionType: Hashable, ItemType: Hashable>: UITableViewDiffableDataSource<SectionType, ItemType> {
  override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
  }
}

struct RoutineTableView: UIViewRepresentable {

  let routines: [Routine]
  private var onCellPress: (() -> Void)? = nil
  private var trailingSwipeActionsConfiguration: (() -> UISwipeActionsConfiguration)? = nil

  init(routines: [Routine]) {
    self.routines = routines
  }

  func makeUIView(
    context: UIViewRepresentableContext<RoutineTableView>
  ) -> UITableView {
    let tableView = UITableView()
    context.coordinator.update(withTableView: tableView)
    return tableView
  }

  func updateUIView(_ uiView: UITableView, context: UIViewRepresentableContext<RoutineTableView>) {
    context.coordinator.update(routines: routines)
  }

  // MARK: - Coordinator

  func makeCoordinator() -> RoutineTableView.Coordinator {
    return Coordinator(self)
  }

  class Coordinator: NSObject, UITableViewDelegate {

    private enum Section {
      case first
    }

    private let view: RoutineTableView
    private var dataSource: UITableViewDiffableDataSource<Section, Routine>?

    init(_ view: RoutineTableView) {
      self.view = view
      super.init()
    }

    func update(withTableView tableView: UITableView) {
      tableView.register(RoutineTableViewCell.self)
      tableView.delegate = self

      let dataSource = CustomDataSource<Section, Routine>(tableView: tableView) { (tableView, indexPath, routine) -> UITableViewCell? in
        let cell: RoutineTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.configure(withRoutine: routine)
        return cell
      }
      self.dataSource = dataSource
    }

    func update(routines: [Routine]) {
      var snapshot = NSDiffableDataSourceSnapshot<Section, Routine>()
      snapshot.appendSections([.first])
      snapshot.appendItems(routines)
      dataSource?.apply(snapshot, animatingDifferences: true)
    }

    // MARK: - <UITableViewDelegate>

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      view.onCellPress?()
    }

    func tableView(
      _ tableView: UITableView,
      trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
    ) -> UISwipeActionsConfiguration? {
      return view.trailingSwipeActionsConfiguration?()
    }

  }
}

extension RoutineTableView {

  func onCellPress(
    _ onCellPress: @escaping () -> Void
  ) -> RoutineTableView {
    var view = self
    view.onCellPress = onCellPress
    return view
  }

  func trailingSwipeActionsConfiguration(
    _ trailingSwipeActionsConfiguration: @escaping () -> UISwipeActionsConfiguration
  ) -> RoutineTableView {
    var view = self
    view.trailingSwipeActionsConfiguration = trailingSwipeActionsConfiguration
    return view
  }
}
...