In the following code I have a couple buttons showing as an inputAccessoryView when inputFieldOne is in editing mode, when you tap First Button, it inputs ONE inside inputFieldOne and when I tap Second Button it inputs TWO inside inputFieldOne. It works as expected but what I would like to be able to do is re-use these buttons in multiple UITextFields. In other words, if I have another UTTextField called inputFieldTwo, I would like to be able to also input the values from those buttons when they're tapped.
How can I keep track of what UITextField is currently in editing mode so I can append the values from the buttons?
@IBOutlet weak var inputFieldOne: UITextField!
@IBOutlet weak var inputFieldTwo: UITextField!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addButtonsToKeyboard()
}
func addButtonsToKeyboard(){
// First button
let button1 = UIButton()
button1.setTitle("First Button", for: UIControl.State())
button1.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton1 = UIBarButtonItem()
barButton1.customView = button1
// Second button
let button2 = UIButton()
button2.setTitle("Second Button", for: UIControl.State())
button2.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton2 = UIBarButtonItem()
barButton2.customView = button2
/// UIToolbar.
let toolBar = UIToolbar()
toolBar.tintColor = UIColor.blue
toolBar.barTintColor = UIColor.red
toolBar.items = [barButton1, barButton2]
toolBar.sizeToFit()
inputFieldOne.inputAccessoryView = toolBar
}
@objc func buttonKeyPress(_ sender: UIButton){
switch sender.currentTitle!{
case "First Button":
inputFieldOne.text = "ONE"
case "Second Button":
inputFieldOne.text = "TWO"
default: break
}
}