Skip to content

Instantly share code, notes, and snippets.

@brindy
Created August 31, 2022 10:04
Show Gist options
  • Save brindy/939bc76a6a39a0584b9c839f351c1bf6 to your computer and use it in GitHub Desktop.
Save brindy/939bc76a6a39a0584b9c839f351c1bf6 to your computer and use it in GitHub Desktop.
Update SwiftUI EditMode from UIKit
//
// ViewController.swift
// EditButtonExample
//
// Created by Chris Brind on 31/08/2022.
//
import UIKit
import SwiftUI
import Combine
// Assumes this ViewController is on a UINavigationViewController stack
class ViewController: UIHostingController<ExampleListView> {
let model = ExampleListModel()
var cancellables = Set<AnyCancellable>()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder, rootView: ExampleListView(model: model))
// This lets us update our UIKit layer when the user swipes to delete an item when not in edit mode
model.$editMode.sink { newEditMode in
if newEditMode == .transient {
self.setupDoneButton()
}
}.store(in: &cancellables)
}
override func viewDidLoad() {
super.viewDidLoad()
setupEditButton()
}
@IBAction func onEdit() {
model.editMode = EditMode.active
setupDoneButton()
}
@IBAction func onDone() {
model.editMode = EditMode.inactive
setupEditButton()
}
private func setupEditButton() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(onEdit))
}
private func setupDoneButton() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDone))
}
}
class ExampleListModel: ObservableObject {
@Published var editMode: EditMode = .inactive
}
struct ExampleListView: View {
@ObservedObject var model: ExampleListModel
let items = ["Hello", "World"]
var body: some View {
List {
Section("Won't show delete prompts") {
Text("Example 1")
}
Section("Can be deleted") {
ForEach(items, id: \.self) { item in
Text(item)
}.onDelete { indexSet in
print("onDelete", indexSet)
}
}
}
// Bind the edit mode environment variable to our model so we can change it from UIKit
.environment(\.editMode, $model.editMode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment