for those who are searching for the answer in Swift 5.
by override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)
method. you can detect device orientation.
here is the code for my custom keyboard.
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
let screen = UIScreen.main.bounds
if screen.width < screen.height {
print("!!! portrait")
let constraintForHeight:NSLayoutConstraint = NSLayoutConstraint(item: mainView!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 325)
constraintForHeight.isActive = true
constraintForHeight.priority = UILayoutPriority.defaultHigh
self.inputView?.addConstraint(constraintForHeight)
} else {
print("!!! landspace")
let constraintForHeight:NSLayoutConstraint = NSLayoutConstraint(item: mainView!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 210)
constraintForHeight.isActive = true
constraintForHeight.priority = UILayoutPriority.defaultHigh
self.inputView?.addConstraint(constraintForHeight)
}
}
viewDidLayoutSubviews
gets called twice upon an orientation change. We only want the method to be called ONCE per orientation change. And with the current method, the second time it is called (which is the time that the proper orientation is finally detectable), the orientation animation has already completed and your keyboard stretch will appear laggy. – Carbolated