swift uitextfield only numbers keyboard lock programmatically

Swift
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // you can set the following two properties for the text field in Interface Builder, if you'd prefer

        textField.delegate = self
        textField.keyboardType = .numberPad
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
        return string.rangeOfCharacter(from: invalidCharacters) == nil
    }

    // or, alternatively:
    //
    // func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    //     return string.range(of: "^\\d*$", options: .regularExpression) != nil
    // }

}
Source

Also in Swift: