Created
September 20, 2024 18:24
-
-
Save coreyd303/9a094be0e42c62ceb15b808ea9a991fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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