iOS OS键盘的底部为文本视图,顶部为搜索栏

时间:2018-08-04 08:07:33

标签: ios keyboard

我在屏幕底部有一个textview,在屏幕顶部有搜索栏。以下是我的代码来解决按下textview时键盘的问题

extension UIView { 
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY

        },completion: {(true) in
            self.layoutIfNeeded()
        })
    }
}

但是,当我按搜索栏时,屏幕将向上移动,搜索栏消失。如果我执行view.bindToKeyboard(),则在显示键盘后,edittext是正确的。

我尝试过的一种解决方案是将textview的出口绑定到键盘,但是一旦我开始键入,textview就会消失。

2 个答案:

答案 0 :(得分:2)

我认为问题是您试图知道何时键盘将出现。搜索栏有一个文本字段。因此,当点击它时,它将像您的文本视图一样打开键盘,并调用 keyboardWillChange

   keyboardWillChange(_ notification: NSNotification)

因此,键盘出现并隐藏您的搜索栏。您可以检测到搜索栏的点击并在那里取消通知。

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool
    {
       //Dismiss your keyboard notification here

       return true
    }

您应该使用库来处理这种情况。我建议 IQKeyboardManager IQKeyBoardManager Github.

答案 1 :(得分:0)

我编辑了我先前的回复...您是否尝试过将searchBar放到NavigationBar中?

类似这样的东西(只需放在viewDidLoad上):

navigationItem.titleView = searchBar