-2

I have an if statement in my app to detect whether or not to move the view up when the keyboard appears. I have a separate one of 3.5/4, 4.7 and 5.5 inch screens.

The ones for the 3.5/4 and 5.5 inch screens work great, however for some reason, the one for the 4.7 inch screen isn't functioning.

This is my code:

    if keyboardActive == false && height == 667 && self.entryView.center.y == 333.5 {

If I remove self.entryView.center.y == 333.5 then it works, so that's the problem. I've tried rounding up to 334 and down to 333 but that didn't help.

Does anyone know why the centre y value is not 333.5?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3746428
  • 11,047
  • 20
  • 81
  • 137

1 Answers1

1

comparing floating point numbers is problematic. See for example: (How should I do floating point comparison?).

Moving your screen based on literals is also problematic. Better would be to get the frame of the keyboard in view local coordinates and resize your view accordingly. Note that if you are using constraints, you will have to adjust the constraints rather than the frame of your view(s).

Here's a handy function I wrote for the purpose:

private func extractKeyboardInfo(userInfo: NSDictionary) -> (keyboardFrame: CGRect, duration: NSTimeInterval, viewAnimationOptions: UIViewAnimationOptions) {
    let globalKeyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
    let localKeyboardFrame = self.view.convertRect(globalKeyboardFrame, fromView: nil)
    let curve = UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).unsignedIntValue << 16)
    let viewAnimationOptions = UIViewAnimationOptions.fromRaw(curve)!
    let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue as NSTimeInterval
    return (localKeyboardFrame, duration, viewAnimationOptions)
}
Community
  • 1
  • 1
Daniel T.
  • 32,821
  • 6
  • 50
  • 72