【发布时间】:2019-07-11 11:53:37
【问题描述】:
我正在尝试制作一个自定义 iOS 键盘,全部包含在 BibleKeyboardView.swift 和 BibleKeyboardView.xib 文件中。视图的一部分包含多个 UITextFields 我想通过数字按钮输入。但是,当我单击任何 UITextField 时,键盘会关闭然后重新出现,光标永远不会停留在 UITextField 中,并且 UIButton 不会执行任何操作。
Gif of the keyboard disappearing/reappearing issue
我已经尝试设置每个 UITextField 的 inputView = self 但这只会让键盘保持关闭状态。我还在情节提要右侧菜单中将每个数字按钮设置为键盘键。
这是我的代码,但是当我尝试运行它时,activeField 为 nil 并引发 Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 错误。该代码永远不会到达textFieldDidBeginEditing(),因为该打印语句没有运行(基于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设置了委托? -
看起来您在将其分配给任何东西之前为 activeField 设置了代理。尝试在每次 textFieldDidBeginEditing 时分配它或为 viewdidLoad 中的 4 个 textField 中的每一个设置它。
-
@Magnas 为 awakeFromNib() 中的每个文本字段设置委托并从 textFieldDidBeginEditing 中删除 activeField?.inputView = self 允许我输入文本字段。谢谢!键盘仍然关闭并重新出现。
-
@DharmeshKheni 当我尝试它时,它使它成为 textFieldDidBeginEditing 功能,但键盘仍然关闭并重新出现。尽管如此,至少现在我可以输入到我的文本字段中。谢谢!
-
你能分享任何我可以检查这个问题的演示项目吗? @AmyFang
标签: ios swift uitextfield custom-keyboard