So I have implemented a textfield which sits at the bottom of the screen. Once the user taps on the textfield, the keyboard comes up and the textfield also sits nicely on the top of the keyboard (like those chat applications)
However, once I either swipe the predictive text on or off (upwards or downwards) the view messes up and and it doesn't sit nicely on the keyboard anymore. How can i solve this?
so far this is my code:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
var _currentKbHeight: CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillChange:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillChange(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
var deltaHeight:CGFloat = keyboardSize.height - _currentKbHeight
UIView.animateWithDuration(0.3, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, -deltaHeight)
})
_currentKbHeight = keyboardSize.height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
UIView.animateWithDuration(0.3, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, keyboardSize.height)
})
_currentKbHeight = 0.0
}
}
}
}
You actually want to override the
inputAccessoryView
property. This is Apple's built-in way of supplying a view like yours that will always sit on top of the keyboard.Here's an example: https://robots.thoughtbot.com/input-accessorizing-uiviewcontroller
Another example: http://derpturkey.com/uitextfield-docked-like-ios-messenger/