2

How can I check if the keyboard is blocking my view?

I have UIButton that is in the centre of the screen. I also have a UITextfield that makes the keyboard appears. When I run the app on iPhone 4 the keyboard block the button, but on other models, it doesn't. I have a method that scrolls up the view when the keyboard appears. But I only want to scroll up in case the view is blocked. I can check the model of the iPhone and then decide if to scroll or not, but I thought checking if the Button is blocked would be better. How can I do it?

bobsacameno
  • 765
  • 3
  • 10
  • 25

4 Answers4

1

I solved this problem in an app like so:

Embed the UI for that screen in a UIScrollView, but configure it so that scrolling is not enabled (scrollEnabled property from code, checkbox if you're using a storyboard).

When the keyboard notification is received, get the frame from the button, then call scrollRectToVisible:animated: on the scroll view. It'll move the content the minimum amount necessary to make the button visible, which will be not at all if the screen is big enough.

dpassage
  • 5,423
  • 3
  • 25
  • 53
1

Using the UIKeyboardWillShowNotification, you can get the height of the keyboard like this:

NSValue *keyboardRect = [notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGFloat keyboardHeight = MIN(keyboardRect.CGRectValue.size.width, keyboardRect.CGRectValue.size.height);

The get the relevant "lowest" point of your button. (like buttonMaxY = CGRectGetMaxY(yourButton.frame)). Use the scroll methods you have implemented, but scroll only if necessary: keyboardHeight+buttonMaxY > the height of the screen.

AntiApple
  • 13
  • 3
0

When keyboard is about to appear, a UIKeyboardWillShowNotification notification is posted with the frame of the keyboard. You can calculate and see if the text field frame intersects with the keyboard frame, and scroll.

See documentation on keyboard notifications here.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
0

Following Leo Natan's explanation, you can try something like:

func keyboardWillShow(notification: Notification) {


    guard let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect,
          let viewFrame = myView.frame else {

        log.error("I cannot calculate keyboard & view frame")
        return
    }

    if keyboardFrame.intersects(viewFrame) {

        // view covered by Keyboard
    }

}

pay attention to use UIKeyboardFrameEndUserInfoKey, you can check this link for further details.

Community
  • 1
  • 1
Claus
  • 5,662
  • 10
  • 77
  • 118