My question is very specifically for iOS 10 and swift 3 as ive tried multiple solutions for this problem but they don't work due to swift 3. I have also tried converting the code and enabling legacy code. All of those doesn't work.
I would really appreciate if you can post the code and simple steps to automatically move the text field up then inputing the text and upon tapping the return key the text field should go back to its original place and keyboard disappear.
Thank you
This example works on Swift 3:
extend UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.nicknameLabel.resignFirstResponder()
return true
}
viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
nicknameLabel.delegate = self
}
Here are some tips that works for Swift 3: https://medium.com/@KaushElsewhere/how-to-dismiss-keyboard-in-a-view-controller-of-ios-3b1bfe973ad1#.2fw5cflmp
First put UITextField in a scroll view.
Then have this little extension:
extension UIScrollView {
/// listen to keyboard event
func makeAwareOfKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
/// move scroll view up
func keyBoardDidShow(notification: Notification) {
let info = notification.userInfo as NSDictionary?
let rectValue = info![UIKeyboardFrameBeginUserInfoKey] as! NSValue
let kbSize = rectValue.cgRectValue.size
let contentInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
self.contentInset = contentInsets
self.scrollIndicatorInsets = contentInsets
}
/// move scrollview back down
func keyBoardDidHide(notification: Notification) {
// restore content inset to 0
let contentInsets = UIEdgeInsetsMake(0, 0, 0, 0)
self.contentInset = contentInsets
self.scrollIndicatiorInsets = contentInsets
}
}
Then make that scroll view aware of keyboard
override func viewDidLoad() {
super.viewDidLoad()
...
scrollView.makeAwareOfKeyboard()
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With