Reputation: 933
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...
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.
Upvotes: 1
Views: 3931
Reputation: 4858
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()
}
Upvotes: 1
Reputation: 2802
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.
Upvotes: 9