ios - 当键盘显示一个文本视图但没有另一个文本视图时如何移动视图
问题描述
我在顶部有一个 UITextView,在中心有一个 UITextView,在底部有一个 UITextView。如果使用底部的 UITextView 或中心的 UITextView,我想在键盘出现时向上移动视图,但是在使用顶部的 UITextView 时,视图不应该移动。
我该如何进行这项工作?
func showLoginKeyBoard()
{
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification)
{
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
{
if self.view.frame.origin.y == 0
{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func textViewDidBeginEditing(_ textView: UITextView)
{
if textView == centreTextView
{
showLoginKeyBoard()
}
if textView == bottomTextView
{
showLoginKeyBoard()
}
}
目前,当任何 UITextViews 成为FirstResponder 时,视图会向上移动,这意味着在使用顶部 UITextView 时它是不可见的。
如何确保顶部 UITextView 不会向上移动视图?
解决方案
在回答您的问题之前,根据您的代码,每次用户单击 textView 时添加观察者。不要这样做。在 viewDidLoad() 中添加观察者,不要忘记在 viewDidDisappear() 中删除观察者。否则会导致内存泄漏。
现在,回答问题
定义文件私有可选文本视图
var currentTextView:UITextView?
然后在textViewDidBeginEditing中分配 textField
func textViewDidBeginEditing(_ textView: UITextView){
currentTextView = textView
}
现在你可以根据 currentTextView 显示或不显示
@objc func keyboardWillShow(notification: NSNotification){
if let txtView = currentTextView{
txtView != topTextView {
//move up the view
}
}
}
推荐阅读
- kubernetes - K8s Master重启后,apiserver报错“x509: certificate has expired or is not yet valid”
- angular - 有没有办法检测用户是否查看了组件?
- c++ - 为什么我的程序继续给我堆缓冲区溢出,即使我没有超出我的数组或覆盖任何值
- laravel - 使用 nginx 设置多站点
- contextmenu - 如何在上下文菜单中隐藏 div/模板元素
- javascript - 是的 punycode 和西里尔字母的域名验证
- html - 如何创建下拉列表以过滤特定列中的行
- javascript - 两个对象之间的差异
- angular - 服务的 SpyObject 上的 Angular 单元测试组件调用
- arrays - 在 JSON 输出中强制将单个结果作为数组