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

送分小仙女□ 提交于 2019-12-02 04:27:32

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.

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