Find out when UIKeyboard.frame intersects with other frame?

℡╲_俬逩灬. 提交于 2019-12-01 13:21:48

问题


I need to find out when the textfield becomes the first responder to notify me whether the keyboard that's going to show will obstruct the UITextField. If it does, I wanna adjust the scrollview properties.

So far I have this setup. I'm listening for UIKeyboardWillShow notifications that calls the following selector:

func keyboardWillAppear(notification:NSNotification)
{
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
    {

        if keyboardSize.intersects(textField.frame)
        {
            print("It intersects")
        }
        else
        {
            print("Houston, we have a problem")
        }
    }

Note: I tried with UIKeyboardDidShow but still no success. UITextField is a subview of the scrollView.


回答1:


  1. listen to size changes of the keyboard
  2. CONVERT the coordinates

working sample:

 @IBOutlet weak var textView: UITextView!
 override func viewDidLoad() {
    super.viewDidLoad()

    //keyboard observers
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}

func keyboardWillChange(notification:NSNotification)
{
    print("Keyboard size changed")

    if let keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
        //convert gotten rect
        let r = self.view.convert(keyboardSize, from: nil)

        //test it
        if r.intersects(textView.frame) {
            print("intersects!!!")
        }
    }
}



回答2:


How about comparing the start position of the keyboard with the end position of the text?

working sample:

func keyboardWillAppear(notification:NSNotification)
{
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
    {
        if keyboardSize.origin.y < textField.frame.origin.y + textField.frame.size.height {
             print("It intersects")
        } else {
            print("Houston, we have a problem")
        }
    }
}


来源:https://stackoverflow.com/questions/42231283/find-out-when-uikeyboard-frame-intersects-with-other-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!