Find out when UIKeyboard.frame intersects with oth

2019-02-21 02:53发布

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.

2条回答
Lonely孤独者°
2楼-- · 2019-02-21 03:02

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")
        }
    }
}
查看更多
祖国的老花朵
3楼-- · 2019-02-21 03:19
  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!!!")
        }
    }
}
查看更多
登录 后发表回答