Hey guys,
I'm trying to add a textfield alert in SwiftUI Via UIKit but its not working inside a PickerView. it works everywhere else
Code:
func createAlert(alertController: UIAlertController, placeholder: String, saveAction: @escaping (String) -> Void) {
let alert = alertController
alert.addTextField { textField in
textField.placeholder = placeholder
}
let saveButton = UIAlertAction(title: "Save", style: .default) { _ in
guard let text = alert.textFields?[0].text else { return }
saveAction(text)
}
let cancel = UIAlertAction(title: "Cancel", style: .default) { _ in
}
alert.addAction(saveButton)
alert.addAction(cancel)
UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true)
}
Usecase:
Picker(selection: $viewModel.recipe.category, label: Text("Cuisine")) {
ForEach(viewModel.categories, id: \.self) {
Text($0)
}
HStack {
Label("Add Cuisine", systemImage: "plus.circle.fill")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.vertical, 13)
.onTapGesture {
createAlert(alertController: UIAlertController(title: "Add Category", message: "", preferredStyle: .alert), placeholder: "Category") { categoryText in
viewModel.categories.append(categoryText)
viewModel.recipe.category = categoryText
}
}
}