Adding a minus sign to the UITextField's .NumberPad keyboard

霸气de小男生 提交于 2019-12-02 11:45:38

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36455158/adding-a-minus-sign-to-the-uitextfields-numberpad-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!