Cepat 3/4
Anda dapat menggunakan ekstensi di bawah ini untuk kenyamanan Anda.
Penggunaan di dalam ViewController
:
showInputDialog(title: "Add number",
subtitle: "Please enter the new number below.",
actionTitle: "Add",
cancelTitle: "Cancel",
inputPlaceholder: "New number",
inputKeyboardType: .numberPad)
{ (input:String?) in
print("The new number is \(input ?? "")")
}
Kode ekstensi:
extension UIViewController {
func showInputDialog(title:String? = nil,
subtitle:String? = nil,
actionTitle:String? = "Add",
cancelTitle:String? = "Cancel",
inputPlaceholder:String? = nil,
inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
actionHandler: ((_ text: String?) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
alert.addTextField { (textField:UITextField) in
textField.placeholder = inputPlaceholder
textField.keyboardType = inputKeyboardType
}
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
guard let textField = alert.textFields?.first else {
actionHandler?(nil)
return
}
actionHandler?(textField.text)
}))
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))
self.present(alert, animated: true, completion: nil)
}
}