Vineeth Krishnan Vineeth Krishnan - 3 months ago 15
Swift Question

How to change the alertcontroller textfield keyboard to numberpad?

Given below is the code for my alertcontroller
I want to make numberpad appear instead of normal keyboard when I type in the textfield.how to do this??

func addPasscodeAlert()
{
let blurEffect = UIBlurEffect(style: .Light)
let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
blurVisualEffectView.frame = view.bounds
self.view.addSubview(blurVisualEffectView)

let alertController = UIAlertController(title: "No passcode saved", message: "Please enter new 4 digit passcode.", preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "OK", style: .Cancel) { (action) -> Void in


if let textField = alertController.textFields?.first as UITextField?
{
textField.keyboardType = UIKeyboardType.NumberPad
self.passcode = textField.text!
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(self.passcode, forKey: "passcode")
self.showPasswordAlert()
}
}

alertController.addAction(defaultAction)

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in

textField.placeholder = "Password"
textField.secureTextEntry = true
}
self.presentViewController(alertController, animated: true, completion: nil)
blurVisualEffectView.removeFromSuperview()


}

Answer

change keyboard type in handler method not in UIAlertAction. replace your code with below.

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    textField.keyboardType = UIKeyboardType.NumberPad
    textField.placeholder = "Password"
    textField.secureTextEntry = true
}