Bom dia!!
Segue uma alternativa:
// MARK: Alinhar campos de acordo com teclado subindo
// This code handles the scrolling when tabbing through input fields
var KEYBOARD_ANIMATION_DURATION: CGFloat = 0.3
var MINIMUM_SCROLL_FRACTION: CGFloat = 0.3
var MAXIMUM_SCROLL_FRACTION: CGFloat = 0.8
var PORTRAIT_KEYBOARD_HEIGHT: CGFloat = 200
var LANDSCAPE_KEYBOARD_HEIGHT: CGFloat = 140
// MARK: UITextField delegates
func initMask(aMask:String) -> Void {
self.mask = aMask
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let textFieldRect: CGRect = self.view.window!.convert(textField.bounds, from: textField)
let viewRect: CGRect = self.view.window!.convert(self.view.bounds, from: self.view)
let midline: CGFloat = textFieldRect.origin.y+0.5*textFieldRect.size.height
let numerator: CGFloat = midline-viewRect.origin.y-MINIMUM_SCROLL_FRACTION*viewRect.size.height
let denominator: CGFloat = (MAXIMUM_SCROLL_FRACTION-MINIMUM_SCROLL_FRACTION)*viewRect.size.height
var heightFraction: CGFloat = numerator/denominator
if heightFraction < 0.0 {
heightFraction = 0.0
} else if heightFraction > 1.0 {
heightFraction = 1.0
}
let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
if orientation == .portrait || orientation == .portraitUpsideDown {
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT*heightFraction)
} else {
animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT*heightFraction)
}
var viewFrame: CGRect = self.view.frame
viewFrame.origin.y -= animatedDistance!
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(TimeInterval(KEYBOARD_ANIMATION_DURATION))
self.view.frame = viewFrame
UIView.commitAnimations()
}
func textFieldDidEndEditing(_ textField: UITextField) {
var viewFrame = self.view.frame
viewFrame.origin.y += animatedDistance!
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(TimeInterval(KEYBOARD_ANIMATION_DURATION))
self.view.frame = viewFrame
UIView.commitAnimations()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}