ios - 仅当键盘覆盖按钮时才向上移动视图
问题描述
当我点击 uitextview 时,我试图移动一个按钮。我使用了一个有效的代码。2tap 后我的按钮上升。
import UIKit
extension UIView{
func bindKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification) {
// Allows for keyframe animation, moving the button up with the keyboard.
// It binds the object with the button
let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
let startingFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endingFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endingFrame.origin.y - startingFrame.origin.y
print(deltaY)
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
}, completion: nil)
}
}
我有一个名为 nextBtn 的按钮。我正在调用 nextBtn.bindKeyboard() 方法。点击后,我得到了一个完美的按钮位置,但是当我尝试点击两次时,我得到了错误的位置。有时我的按钮不会向上移动。我不是以英语为母语的人。如果我犯了任何语法错误,请原谅我。 在第一次点击 textview 之后
解决方案
如果尚未设置到该位置,则设置框架
extension UIView{
func bindKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification) {
// Allows for keyframe animation, moving the button up with the keyboard.
// It binds the object with the button
let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
let startingFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endingFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endingFrame.origin.y - startingFrame.origin.y
print(deltaY)
if self.frame.origin.y == 0 {
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
}, completion: nil)
}
}
}
在 didLoad 中添加绑定
override func viewDidLoad() {
super.viewDidLoad()
nextBtn.bindKeyboard()
goalTextView.delegate=self
// Do any additional setup after loading the view.
}
从...除去textViewDidBeginEditing
推荐阅读
- numpy - 如何使用 Keras 将输入和输出数据拟合到连体网络中?
- angular - 2 以角度输入指令
- html - 如何解决我的网址被更改的问题
- mysql - 带有 where 子句的内部连接不需要的结果
- javascript - 在字符串/消息中查找单词短语(不仅仅是单个单词,而是一个句子)并从数组返回响应
- javascript - 如何将对象添加到数组并在用户单击时将其删除?
- nginx - 如何在剖析查询字符串时进行 nginx 重定向?
- jquery - 未捕获的类型错误:无法读取未定义的属性“innerHTML”,如果跨度文本为空
- android - 创建一个可折叠的侧边栏 - 导航抽屉的替代品?
- oracle - 如何知道用户被授予必要的权限以充当恢复目录所有者 (Oracle 12c)