Created
September 13, 2020 05:15
-
-
Save foxicode/8cb7a5479af942e4f7dcc3c8cd6841be to your computer and use it in GitHub Desktop.
Ask user for a number in Swift (iOS)
This file contains hidden or 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 UIKit | |
| extension UIViewController { | |
| func ask(title: String?, question: String?, placeholder: String?, keyboardType: UIKeyboardType = .default, delegate: @escaping (_ answer: String?) -> Void) { | |
| let alert = UIAlertController(title: title, message: question, preferredStyle: .alert) | |
| alert.addTextField { (textField) in | |
| textField.placeholder = placeholder | |
| textField.keyboardType = keyboardType | |
| } | |
| alert.addAction(UIAlertAction(title: "OK", style: .default) { (_) in | |
| let answer = alert.textFields?.first?.text | |
| delegate(answer) | |
| }) | |
| alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (_) in | |
| delegate(nil) | |
| }) | |
| present(alert, animated: true, completion: nil) | |
| } | |
| func askNumber(title: String?, question: String?, placeholder: String?, delegate: @escaping (_ answer: Int?) -> Void) { | |
| ask(title: title, question: question, placeholder: placeholder, keyboardType: .numberPad) { (result) in | |
| if let result = result, | |
| let iResult = Int(result) { | |
| delegate(iResult) | |
| } else { | |
| delegate(nil) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment