Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - iOS 10 - UITextField - how to auto hide keyboard and auto move the text field up

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

like image 255
Umair Avatar asked Jan 05 '23 07:01

Umair


2 Answers

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

like image 130
kavehmb Avatar answered Jan 07 '23 21:01

kavehmb


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()
    ...
}
like image 31
Fitsyu Avatar answered Jan 07 '23 21:01

Fitsyu