Swift 3 - iOS 10 - UITextField - how to automatically hide the keyboard and automatically move the text box up

My question is very specific for iOS 10 and swift 3, since ive tried several solutions for this problem, but they do not work because of quick 3. I also tried to convert the code and include the outdated code. All this does not work.

I would really appreciate it if you could publish the code and simple steps to automatically move the text field and then enter the text, and when you press the return key, the text field should return to its original location and the keyboard will disappear.

thank

+4
source share
2 answers

This example works in Swift 3:

extend UITextFieldDelegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.nicknameLabel.resignFirstResponder()
        return true
    }

viewDidLoad:

override func viewDidLoad() {
        super.viewDidLoad()
        nicknameLabel.delegate = self
    }

, Swift 3: https://medium.com/@KaushElsewhere/how-to-dismiss-keyboard-in-a-view-controller-of-ios-3b1bfe973ad1#.2fw5cflmp

+7

UITextField .

:

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
 }
}

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    scrollView.makeAwareOfKeyboard()
    ...
}
+2

Source: https://habr.com/ru/post/1655648/


All Articles