跟踪哪个 UITextField 当前处于编辑模式
Posted
技术标签:
【中文标题】跟踪哪个 UITextField 当前处于编辑模式【英文标题】:Keep track of which UITextField is currently in editing mode 【发布时间】:2019-11-25 14:01:55 【问题描述】:在下面的代码中,当inputFieldOne
处于编辑模式时,我有几个按钮显示为inputAccessoryView
,当您点击First Button
时,它会在inputFieldOne
中输入ONE
,当我点击Second Button
时它在inputFieldOne
中输入TWO
。它按预期工作,但我希望能够在多个UITextFields
中重复使用这些按钮。换句话说,如果我有另一个名为inputFieldTwo
的UTTextField
,我希望能够在这些按钮被点击时输入它们的值。
如何跟踪 UITextField
当前处于编辑模式的内容,以便我可以附加按钮中的值?
@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
【问题讨论】:
【参考方案1】:有很多方法可以使其可重复使用,因为我的时间非常有限,所以我建议你可以使用 Extension
你可以为你所有的文本字段使用它
所以这里是sn-p的代码:
extension UITextField
// you can pass here array of UIbarbutton also
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()
self.inputAccessoryView = toolBar
@objc func buttonKeyPress(_ sender: UIButton)
switch sender.currentTitle!
case "First Button":
self.text = "ONE"
case "Second Button":
self.text = "TWO"
default: break
您可以使用文本字段对象添加以下代码
txtSwift.addButtonsToKeyboard()
希望对你有帮助!!!
【讨论】:
以上是关于跟踪哪个 UITextField 当前处于编辑模式的主要内容,如果未能解决你的问题,请参考以下文章
如何在自定义 UITableViewCell 中控制 UITextFields 的编辑