ios - 将 textField 更改为 textView 时出现问题?
问题描述
我有一个带有几个文本字段的 viewController。然后过了一会儿,我发现真的没有办法让 textFields 变成多行(如果你问我的话,真傻!)。
所以我把所有的 textFields 都改成了 textViews,这样用户就可以写几行了。现在,之前我有很多代码组合到这些 textFields 上,因为让 textField 根据keyboardSize 上下移动的复杂性等等。
奇怪的是,我认为我可以将所有单词“textField”更改为 textView - 然后键盘的行为方式相同。我不能。这是我的代码(更改为尝试适应我的新 textViews 而不是旧的 textFields):
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardDidShow(notification: NSNotification) {
let info:NSDictionary = notification.userInfo! as NSDictionary
let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardY = self.view.frame.height - keyboardSize.height
let editingTextFieldY:CGFloat! = self.activeTextView.frame.origin.y
if self.view.frame.origin.y >= 0 {
// Checking if the textfield is really being hidden:
if editingTextFieldY > keyboardY - 60 {
UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.view.frame = CGRect(x: 0, y: self.view.frame.origin.y - (editingTextFieldY - (keyboardY - 60)), width: self.view.bounds.width, height: self.view.bounds.height)
}, completion: nil)
} } }
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
}, completion: nil)
}
该应用程序编译得很好,但是当我按任何 textView 输入输入时,而不是弹出键盘,应用程序崩溃了,我得到:“线程 1:致命错误:在展开可选值时意外发现 nil”。
这出现在 'let keyboardSize = ...' 行
谁能看到我的错误?或者告诉我另一种根据键盘移动视图的方法 - 使用 textViews 而不是 textFields 时?
另外一点……谁能向我解释一下,为什么同时存在“textField”和“textView”?为什么以上帝的名义,让苹果不只是把这些东西放在一起呢?..
预先感谢!:)
解决方案
使用 pod IQKeyboardManager
在开发 iOS 应用时,我们经常会遇到 iPhone 键盘向上滑动并覆盖 UITextField/UITextView 的问题。
IQKeyboardManager
允许您防止键盘向上滑动和覆盖的问题,UITextField/UITextView
而无需您编写任何代码或进行任何额外的设置。要使用IQKeyboardManager
,您只需将源文件添加到您的项目中。
推荐阅读
- python - 如何计算熊猫数据框中最常见的 500 个单词
- domain-driven-design - DomainEventPublisher 一致性
- c# - 如何检查控制器每个动作的会话?
- javascript - 隐藏手机面包屑导航中的最后一个文本块 - Prestashop
- java - 在 div 类中捕获元素
- javascript - this.setState 是否在反应中返回承诺
- ruby - 合并多个数组
- python - Python 请求与我的数据字典中的链接混淆
- javascript - 无法读取未定义反应js的属性'func'?
- c# - 如何使用 ExecuteScalar() 获取一个值并将其提供给您的 textbox.text?