Is there a UITextField keyboard type that like a number pad but allows negative numbers?

AndyW picture AndyW · Dec 3, 2014 · Viewed 10.9k times · Source

I am setting the UIKeyboardType as UIKeyboardTypeNumberPad on my UITextFields. However, this only allows the user to enter positive integers. I need the user to be able to enter negative or positive integers. Is there a UIKeyboardType that is identical to UIKeyboardTypeNumberPad but also includes the "-" (minus) symbol, and if not is there a way I can create this?

Thanks.

Answer

Locutus picture Locutus · Sep 11, 2019

Here's a version in Swift that has a +/- button and also a Clear and Done button for the numeric keyboard.

numeric keyboard screenshot

extension UITextField {

func addNumericAccessory(addPlusMinus: Bool) {
    let numberToolbar = UIToolbar()
    numberToolbar.barStyle = UIBarStyle.default

    var accessories : [UIBarButtonItem] = []

    if addPlusMinus {
        accessories.append(UIBarButtonItem(title: "+/-", style: UIBarButtonItem.Style.plain, target: self, action: #selector(plusMinusPressed)))
        accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))   //add padding after
    }

    accessories.append(UIBarButtonItem(title: "Clear", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadClear)))
    accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))   //add padding space
    accessories.append(UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadDone)))

    numberToolbar.items = accessories
    numberToolbar.sizeToFit()

    inputAccessoryView = numberToolbar
}

@objc func numberPadDone() {
    self.resignFirstResponder()
}

@objc func numberPadClear() {
    self.text = ""
}

@objc func plusMinusPressed() {
    guard let currentText = self.text else {
        return
    }
    if currentText.hasPrefix("-") {
        let offsetIndex = currentText.index(currentText.startIndex, offsetBy: 1)
        let substring = currentText[offsetIndex...]  //remove first character
        self.text = String(substring)
    }
    else {
        self.text = "-" + currentText
    }
}

}