今天在写评论页面,需要实现评论框和页面一起动起来
使用固定高度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| enum Move { case up case down }
func animatetextView(textView: UITextView, move: Move) { let movementDistance:CGFloat = -350 let movementDuration: Double = 0.3
var movement:CGFloat = 0 if move == .up { movement = movementDistance } else { movement = -movementDistance }
UIView.animate(withDuration: movementDuration) { self.commentView.frame = self.commentView.frame.offsetBy(dx: 0, dy: movement)
} }
|
这就得靠手感了得一个个测,引用方法是UITextView的delegate
的textViewDidBeginEditing(_ textView: UITextView)
方法和textViewDidEndEditing(_ textView: UITextView)
方法
至于关闭编辑,override ViewController
的touchesBegan方法,让textView关闭编辑就好了
通过观察者获取值
在viewDidLoad
里面添加
1 2
| NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(note:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDisappear(note:)), name: UIResponder.keyboardWillHideNotification, object: nil)
|
通过其知道什么时候键盘的打开和关闭
然后实现对应的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @objc func keyboardShow(note: Notification) { guard let userInfo = note.userInfo else {return} guard let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else{return} UIView.animate(withDuration: 5) { self.commentView.transform = CGAffineTransform.init(translationX: 0, y: -keyboardRect.height) } } @objc func keyboardDisappear(note: Notification) { guard let userInfo = note.userInfo else {return} guard let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else{return} UIView.animate(withDuration: 5) { self.commentView.transform = CGAffineTransform.identity } }
|
本来我看的文档里还需要获取keyboard的动画时间,不过试了一下似乎不需要,应该是改进了吧