swift Swift - 修复键盘隐藏UITextFieldimport UIKit类WelcomeViewController:UIViewController,UITextFieldDeleg

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift - 修复键盘隐藏UITextFieldimport UIKit类WelcomeViewController:UIViewController,UITextFieldDeleg相关的知识,希望对你有一定的参考价值。

See: 
//  http://www.swiftexample.info/snippet/swift/movekeyboardupswift_marquavious_swift
//  https://stackoverflow.com/questions/30918732/how-to-determine-which-textfield-is-active-swift

01. Add your textfields,create outlets, and set tag property to 1 for those text fields that
    would be hidden by the keyboard.
02. Embed the fields in a stackview and pin this to the safe edges of the screen.
03. Add UITextFieldDelegate to your class
04. In func setTextFieldDelegates(), enable delegation to all UITextFields


import UIKit

class WelcomeViewController: UIViewController, UITextFieldDelegate {

    var activeTextField = UITextField()          //Create variable to hold the currently active UITextField. It is set in func textFieldDidBeginEditing

    
    @IBOutlet weak var userIdTextField: UITextField!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var pwdTextField: UITextField!
    @IBOutlet weak var pwdChkTextField: UITextField!
    @IBOutlet weak var registerBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTextFieldDelegates()                 //Set all UITextField delegates
        self.hideKeyboardWhenTappedAround()     //Add recognizer to hide keyboard with user taps outside of field with input
        addObserverToKeyboard()                 //Add observers to signal when keyboard shows and hides

    }

    // MARK: Remove all observers before closing
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

}

extension WelcomeViewController {
 
    // MARK: Textfield - Setup delegation for every UITextfield
    func setTextFieldDelegates() {
        userIdTextField.delegate = self
        emailTextField.delegate = self
        pwdTextField.delegate = self
        pwdChkTextField.delegate = self
    }

    // MARK: Textfields - Assign the newly active textField to the activeTextField variable
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.activeTextField = textField
        print ("Boom")
    }
    
    // MARK: Add observers to signal when keyboard shows and hides
    func addObserverToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    // MARK: Check if activeTextField tag property is > 0 and if so, move the superview up.
    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if activeTextField.tag > 0 {
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }
    
    // MARK: Reset the superview that was scrolled up (or not) to x,y origins of 0,0
    @objc func keyboardWillHide(notification: NSNotification) {
        if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.view.frame.origin.y = 0.0
        }
    }
    
    // MARK: Add recognizer to hide keyboard with user taps outside of field with input
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

以上是关于swift Swift - 修复键盘隐藏UITextFieldimport UIKit类WelcomeViewController:UIViewController,UITextFieldDeleg的主要内容,如果未能解决你的问题,请参考以下文章

swift Swift - 隐藏键盘

swift Swift - 用户触摸屏幕时隐藏键盘

swift Swift - 当UITextField被键盘隐藏时滚动查看

Swift:UITextField 被键盘隐藏

Swift:仅当键盘隐藏 TextField 或 Button 时滚动视图

swift 隐藏键盘