1

Fairly new to iOS development so forgive me for asking something that might be quite obvious. As you all know the UITextField's keyboard with keyboardType set to .NumberPad looks like the following...

.NumberPad keyboard

What I would like to do is replace the empty space in the lower left corner with a minus sign. Is this possible or does one need to write an entire custom keyboard to achieve this?

Would really appreciate the help.

zc246
  • 1,514
  • 16
  • 28
  • 1
    Theoretically you could follow [this](http://stackoverflow.com/a/20233101/2710486) but it's not really 'safe' to do it. You may want to try a custom keyboard, or add an extra button within accessoryView. – zc246 Apr 06 '16 at 15:23

2 Answers2

9

Add a toolbar to your textfield inputAccessoryView and when the textfield will become the responder then the keyboard will show the toolbar (Swift 3.0):

func addToolBar(){
   let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44))
   let minusButton = UIBarButtonItem(title: "-", style: .plain, target: self, action: #selector(toggleMinus))
   toolbar.items = [minusButton]
   theTextField.inputAccessoryView = toolbar
}

func toggleMinus(){

    // Get text from text field
    if var text = theTextField.text , text.isEmpty == false{

        // Toggle
        if text.hasPrefix("-") {
            text = text.replacingOccurrences(of: "-", with: "")
        }
        else
        {
            text = "-\(text)"
        }

        // Set text in text field
        theTextField.text = text

    }
}

hope it helps.

Oleg Sherman
  • 2,772
  • 1
  • 21
  • 20
  • How would I make it actually insert the minus button to the text? – Amit Kalra Aug 21 '16 at 20:07
  • You do that in the toggleMinus function. This use of buttons seems to be the common workaround for this problem. But if the user has Button Shapes turned on in accessibility, these buttons will display with underlines. The rest of the keyboard does not. So I think this is not a good solution. – Victor Engel Oct 29 '17 at 01:35
1

Swift 5.2

Set up the UIToolbar as described above and then use an extension on UITextField:

import UIKit

extension UITextField {
    func toggleMinus() {
        guard let text = self.text, !text.isEmpty else { return }
        self.text = String(text.hasPrefix("-") ? text.dropFirst() : "-\(text)")
    }
}

Usage:

@objc func toggleMinus() {
    yourTextField.toggleMinus()
}
rbaldwin
  • 4,581
  • 27
  • 38