当我开始编辑UITextView
时,我正在使用此代码滚动视图。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
但是,我在此视图的顶部也有一个UITextField
,当我开始编辑它时,视图也会滚动。我不希望这种情况发生。如何将代码更改为仅在UITextView
键盘处于活动状态时滚动,而不是在UITextField
键盘激活时滚动?
答案 0 :(得分:1)
试试这段代码,用户textview delgate
// scrollBy - 传递键盘出现时滚动滚动视图的高度
func textViewDidBeginEditing(_ textView: UITextView)
{
scrView.setContentOffset(CGPoint.init(x: 0, y: scrollBy), animated: true)
}
func textViewDidEndEditing(_ textView: UITextView)
{
scrView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)
self.view.endEditing(true);
}
答案 1 :(得分:-3)
而不是编码我建议您在项目中添加TPkeyboard文件,这将在需要时切换键盘