我正在尝试制作一个自定义的iOS键盘,全部包含在BibleKeyboardView.swift
和BibleKeyboardView.xib
文件中。部分视图包含多个UITextField,我想通过数字按钮输入。但是,当我单击任何UITextField时,键盘关闭然后重新出现,光标永远不会停留在UITextField中,并且UIButtons不会执行任何操作。
Gif of the keyboard disappearing/reappearing issue
我已经尝试设置每个UITextField的inputView = self
,但只保持键盘关闭。我还在故事板右侧菜单中将每个数字按钮设置为键盘键。
这是我的代码,但是当我尝试运行它时,activeField
为零并抛出Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
错误。代码从未进入textFieldDidBeginEditing()
,因为print语句不运行(基于How to add text to an active UITextField)。
activeField is nil error screenshot
class BibleKeyboardView: UIView, UITextFieldDelegate {
@IBOutlet weak var chapterA: UITextField!
@IBOutlet weak var verseA: UITextField!
@IBOutlet weak var chapterB: UITextField!
@IBOutlet weak var verseB: UITextField!
var activeField: UITextField?
override func awakeFromNib() {
super.awakeFromNib()
activeField?.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
activeField?.inputView = self
print("made active field")
}
@IBAction func numBtnTapped(_ sender: UIButton) {
activeField!.text = activeField!.text! + (sender.titleLabel?.text!)!
}
我的梦想是,当使用我编码的数字键盘点击时,我可以在每个UITextField中输入数字。当我点击UITextField时,为什么键盘会一直消失并再次出现?为什么textFieldDidBeginEditing没有运行?
最后的答案是:在UITextField
中为每个awakeFromNib()
设置委托和inputView。此外,似乎键盘关闭/重新出现的问题只发生在iPad模拟器上,但是当我在实际的iPad上运行它时它会消失。
class BibleKeyboardView: UIView, UITextFieldDelegate {
@IBOutlet weak var chapterA: UITextField!
@IBOutlet weak var verseA: UITextField!
@IBOutlet weak var chapterB: UITextField!
@IBOutlet weak var verseB: UITextField!
var activeField: UITextField?
override func awakeFromNib() {
super.awakeFromNib()
chapterA.delegate = self
chapterA.inputView = self
verseA.delegate = self
verseA.inputView = self
chapterB.delegate = self
chapterB.inputView = self
verseB.delegate = self
verseB.inputView = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
@IBAction func numBtnTapped(_ sender: UIButton) {
activeField!.text = activeField!.text! + (sender.titleLabel?.text!)!
}
}