首页 > 解决方案 > 使用UIButtons在自定义键盘中输入UITextFields,键盘重新出现,不输入文本

问题描述

我正在尝试制作一个自定义的 iOS 键盘,所有这些都包含在BibleKeyboardView.swiftandBibleKeyboardView.xib文件中。视图的一部分包含多个 UITextFields 我想通过数字按钮输入。但是,当我单击任何 UITextFields 时,键盘关闭然后重新出现,光标永远不会停留在 UITextField 中,并且 UIButtons 不执行任何操作。

键盘消失/重新出现问题的 Gif

我已经尝试设置每个 UITextField inputView = self,但这只会让键盘保持关闭状态。我还将每个数字按钮设置为情节提要右侧菜单中的键盘键。

这是我的代码,但是当我尝试运行它时,它activeField是 nil 并引发Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value错误。代码永远不会成功,textFieldDidBeginEditing()因为该 print 语句没有运行(基于How to add text to an active UITextField)。

activeField 为 nil 错误截图

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 没有运行?

标签: iosswiftuitextfieldcustom-keyboard

解决方案


UITextField最终的答案:为每个 inside 设置 delegate 和 inputView awakeFromNib()。此外,似乎键盘关闭/重新出现的问题只发生在 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!)!
    }
}

推荐阅读