如何配置PDFView表单字段的键盘设置(禁用自动更正)
解决PDFView表单字段禁用拼写自动更正和预测文本的问题
嘿,这个需求我之前做教育类APP的时候刚好碰到过!因为PDFView里的表单字段不像常规的UITextField那样直接暴露autocorrectionType这类属性,所以得绕个小弯来实现,给你分享两个靠谱的方案:
方案一:利用PDFViewDelegate拦截编辑事件(推荐)
PDFView提供了代理方法可以监听表单字段的编辑开始事件,我们可以在这个时机拿到对应的表单注解(PDFWidgetAnnotation),它内部的textInput对象遵循UITextInput协议,我们可以通过KVC来设置自动更正和预测文本的属性:
extension YourViewController: PDFViewDelegate { func pdfViewWillBeginEditingAnnotation(_ pdfView: PDFView, annotation: PDFAnnotation) { // 先判断是不是可编辑的表单字段注解 guard let widgetAnnotation = annotation as? PDFWidgetAnnotation, let textInput = widgetAnnotation.textInput else { return } // 禁用拼写自动更正 textInput.setValue(UITextAutocorrectionType.no.rawValue, forKey: "autocorrectionType") // 禁用预测文本 textInput.setValue(false, forKey: "predictionEnabled") // 可选:如果需要关闭自动大写,也可以加上这行 textInput.setValue(UITextAutocapitalizationType.none.rawValue, forKey: "autocapitalizationType") } }
别忘了在初始化PDFView的时候设置代理:
pdfView.delegate = self
这个方法的优势是精准对应到PDF的表单字段,不会影响APP里的其他输入控件,而且响应时机准确,在用户开始编辑前就完成了设置。
方案二:通过监听键盘事件全局处理
如果方案一在某些iOS版本上有兼容性问题(比如极少数旧版本),可以试试通过监听键盘弹出事件,找到当前的第一响应者,判断是PDF相关的输入控件后设置属性:
override func viewDidLoad() { super.viewDidLoad() // 注册键盘弹出通知 NotificationCenter.default.addObserver( self, selector: #selector(disablePDFInputAutocorrection), name: UIResponder.keyboardWillShowNotification, object: nil ) } @objc private func disablePDFInputAutocorrection() { guard let firstResponder = UIResponder.currentFirstResponder(), // 通过类名判断是不是PDF的输入控件(内部类名一般包含PDF前缀) firstResponder.className.contains("PDF") else { return } // 禁用自动更正和预测文本 firstResponder.setValue(UITextAutocorrectionType.no.rawValue, forKey: "autocorrectionType") firstResponder.setValue(false, forKey: "predictionEnabled") } // 给UIResponder加个扩展,方便获取当前第一响应者 extension UIResponder { static func currentFirstResponder() -> UIResponder? { _currentFirstResponder = nil UIApplication.shared.sendAction(#selector(findFirstResponder(_:)), to: nil, from: nil, for: nil) return _currentFirstResponder } private static weak var _currentFirstResponder: UIResponder? @objc private func findFirstResponder(_ sender: Any) { UIResponder._currentFirstResponder = self } }
这个方法的优点是覆盖场景广,缺点是依赖内部类名判断,可能随着iOS版本更新有变化,所以优先推荐方案一。
需要注意的是,这两种方法都是通过KVC来设置属性,因为Apple没有公开PDF表单输入控件的这些配置接口,所以建议在目标iOS版本上充分测试,目前iOS13及以上版本都能稳定运行。
内容的提问来源于stack exchange,提问作者Mitch Cohen
相关产品推荐
相关产品推荐

