ios - 使用UIButtons在自定义键盘中输入UITextFields,键盘重新出现,不输入文本
问题描述
我正在尝试制作一个自定义的 iOS 键盘,所有这些都包含在BibleKeyboardView.swift
andBibleKeyboardView.xib
文件中。视图的一部分包含多个 UITextFields 我想通过数字按钮输入。但是,当我单击任何 UITextFields 时,键盘关闭然后重新出现,光标永远不会停留在 UITextField 中,并且 UIButtons 不执行任何操作。
我已经尝试设置每个 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)。
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
最终的答案:为每个 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!)!
}
}
推荐阅读
- python - 按列名合并两个 cvs 文件
- java - 由于 entityManagerFactory bean 创建失败,Cloud Foundry 上的应用程序部署失败
- scala - spark 1.6.3 与 Kafka 1.0.0 兼容吗?
- android - 使用特定用户登录 Firebase 实时数据库
- java - 如何从回收视图中保存选定项目的状态?
- spring - 一旦在 Spring 中调用 Endpoint,如何创建一个侦听客户端连接并打开套接字的套接字服务器?
- c# - 使用 Stream vs byte[] 传输文件内容的困惑
- mongodb - 在 MongoDB 中使用 GROUP BY 进行 INNER JOIN
- sql - 生成行计数,每行增加 10,000
- ruby-on-rails - 从 Vuejs 应用程序向 Rails Api 发送表单时完成 422 Unprocessable_entity