Skip to content

Instantly share code, notes, and snippets.

@hmhmsh
Created October 9, 2018 10:34
Show Gist options
  • Save hmhmsh/f491a5ab4032b05f3cde71338278f12f to your computer and use it in GitHub Desktop.
Save hmhmsh/f491a5ab4032b05f3cde71338278f12f to your computer and use it in GitHub Desktop.
UIAlertController with TextField
struct TextAlertController {
func create(title: String, message: String, preferredStyle: UIAlertController.Style = .alert, defaultText: String? = nil, completion: @escaping (String?) -> Void) -> UIAlertController {
let actionController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak actionController] (_) -> Void in
guard let textField = actionController?.textFields?.first else {
completion(nil)
return
}
guard let text = textField.text,
text.count > 0 else {
completion(nil)
return
}
completion(text)
})
actionController.addAction(ok)
let cancel = UIAlertAction(title: "キャンセル", style: .cancel, handler: nil)
actionController.addAction(cancel)
actionController.addTextField { textField in
textField.text = defaultText
}
return actionController
}
}
let textAlertController = TextAlertController().create(title: "Item名の変更", message: "Item名を入力してください", defaultText: label?.text) { [weak self] text in
guard let text = text else {
return
}
self?.label?.text = text
}
self.present(textAlertController, animated: true, completion: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment