Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created September 13, 2020 05:15
Show Gist options
  • Select an option

  • Save foxicode/8cb7a5479af942e4f7dcc3c8cd6841be to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/8cb7a5479af942e4f7dcc3c8cd6841be to your computer and use it in GitHub Desktop.
Ask user for a number in Swift (iOS)
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