How to get the current and correct width in my custom keyboard extension

Viewed 82

I’m building a custom keyboard I’m having a hard time figuring out how to calculate the width of the screen.

What I’m doing:

I calculate the dimensions of my keyboard in a function where I check whether the device is in portrait or landscape mode:

 let screen = UIScreen.main.bounds
 if screen.width < screen.height { //Portrait

} else{  //Landscape

}
  • When the device is in portrait I calculate the buttons width dividing for the width of the screen.
  • When the device is in landscape I calculate the buttons dimensions dividing for the HEIGHT of the screen because when rotating the screen it considers the height to be the keyboard width.

Then in my UIInputViewController I use the function

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {

}

to update the constraints and the dimensions when I rotate the screen.


By logic I’d check for the device’s width and divide it to get the buttons width. The problem is that if I do that, there are issues when I rotate the screen:

  • If I open the keyboard on landscape mode, the width of the buttons is incorrect because the screen height is considered to be the portrait device width (as I stated above).
  • If I use view.frame.width the width I get is 0 unless I call it in viewDidLayoutSubviews. But I need to call it elsewhere.

If I open the keyboard and it is in portrait mode and then I turn the device in landscape mode everything works as expected.

So is there a way to always get the right and current keyboard width in a custom keyboard?

0 Answers
Related