Skip to content

Instantly share code, notes, and snippets.

@coreyd303
Created September 20, 2024 18:24
Show Gist options
  • Save coreyd303/9a094be0e42c62ceb15b808ea9a991fd to your computer and use it in GitHub Desktop.
Save coreyd303/9a094be0e42c62ceb15b808ea9a991fd to your computer and use it in GitHub Desktop.
import SwiftUI
struct OldTableView: UIViewControllerRepresentable {
let onRowSelected: (String) -> Void
let data: [String]
@Binding var reload: Bool
@Environment(\.dismiss) private var dismiss
func makeCoordinator() -> Coordinator {
Coordinator(
onRowSelected: onRowSelected,
data: data,
dismiss: { dismiss() }
)
}
func makeUIViewController(context: Context) -> UITableViewController {
let viewController = UITableViewController()
viewController.tableView.delegate = context.coordinator
viewController.tableView.dataSource = context.coordinator
return viewController
}
func updateUIViewController(_ viewController: UITableViewController, context: Context) {
if reload {
viewController.tableView.reloadData()
}
}
final class Coordinator: NSObject, UITableViewDelegate, UITableViewDataSource {
private let dismiss: () -> Void
let onRowSelected: (String) -> Void
var data: [String]
init(
onRowSelected: @escaping (String) -> Void,
data: [String],
dismiss: @escaping () -> Void
) {
self.onRowSelected = onRowSelected
self.data = data
self.dismiss = dismiss
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let data = data[indexPath.row]
onRowSelected(data)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell")
if (cell == nil) {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = data[indexPath.row]
return cell!
}
}
}
#Preview {
struct Preview: View {
@State var reload = false
var body: some View {
OldTableView(
onRowSelected: { data in
print("data: \(data)")
},
data: [
"ability",
"able",
"about",
"above",
"accept",
"according",
"account",
"across",
], reload: $reload
)
.onAppear {
reload = true
}
}
}
return Preview()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment