【问题标题】:Scroll view when keyboard appears for UITextView, but not for the UITextField that's on the same view当 UITextView 出现键盘时滚动视图,但不在同一视图上的 UITextField
【发布时间】:2017-05-27 02:24:36
【问题描述】:

当我开始编辑 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 键盘被激活时滚动?

【问题讨论】:

  • 不要通过键盘高度改变原点来盲目滚动。计算是否需要滚动以及滚动多少才能使新的第一响应者可见。

标签: ios swift keyboard uitextfield uitextview


【解决方案1】:

试试这段代码,user 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);
    }

【讨论】:

  • 谢谢!我会试试的。
【解决方案2】:

我建议你应该在项目中添加 TPkeyboard 文件而不是编码,这将在需要时切换键盘

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-19
    • 2012-10-10
    • 2011-09-02
    • 2014-08-20
    • 2012-06-29
    • 2015-10-19
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多