I'm developing a custom keyboard extension and noticed when I call self.inputView.frame.size.width
in either viewDidLoad
or viewWillAppear
, it returns 0 or an incorrect number. Only in viewDidAppear
is it correct. This is a problem because I need to update the size of elements in the keyboard based on the available width and height. Right now I am handling this by detecting the frame size in viewWillLayoutSubviews
, which is called several times before it is correct. This works, but the user can see the elements changing size in the keyboard - the frame is not correct until after it has been presented to the user. This is also a problem because I need to update the scroll position once the elements are their correct size, so I'm forced to delay that until viewDidAppear
. This isn't a great user experience with things jumping around after it's been presented.
Is there any way I could know the height and width of the keyboard earlier in the life cycle so I can set the size of the elements before they become visible to the user?
I am using a XIB to create the keyboard interface which utilizes Auto Layout. This is how I add it to the keyboard:
let keyboardNib = UINib(nibName: "KeyboardView", bundle: nil)
let keyboardInterface = keyboardNib.instantiateWithOwner(self, options: nil)[0] as! UIView
keyboardInterface.setTranslatesAutoresizingMaskIntoConstraints(false)
self.inputView.addSubview(keyboardInterface)
let verticalConstraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[keyboardInterface]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["keyboardInterface": keyboardInterface, "view": view]) as! [NSLayoutConstraint]
let horizontalConstraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[keyboardInterface]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["keyboardInterface": keyboardInterface]) as! [NSLayoutConstraint]
self.inputView.addConstraints(verticalConstraints)
self.inputView.addConstraints(horizontalConstraints)