Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 906
AndyW Avatar asked Dec 03 '14 12:12

AndyW


2 Answers

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
    }
}

}
like image 66
Locutus Avatar answered Nov 09 '22 23:11

Locutus


Annoying as it is, there is no such system keyboard available. Other than creating a custom keyboard your best bet is UIKeyboardTypeNumbersAndPunctuation, and doing validation to enforce valid numeric entry.

like image 24
Clafou Avatar answered Nov 09 '22 23:11

Clafou