簡體   English   中英

快速處理鍵盤重疊

[英]handling keyboard overlappingin swift

在沒有 IQKeyboardManagerSwift 或 IHKeyboardAvoiding 等框架的情況下修復鍵盤重疊的最佳方法是什么?

設置您的滾動視圖底部布局約束,

這使得通過滾動可以使用所有文本字段,並且您無需考慮其他設備和鍵盤高度差異。

@IBOutlet weak var mainScrollViewBottomConstraint: NSLayoutConstraint!

 open override func viewDidLoad() {
        super.viewDidLoad()
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

         notificationCenter.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(_ notification: Notification) {
        let userInfo = (notification as NSNotification).userInfo!
        let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        mainScrollViewBottomConstraint.constant = keyboardSize.height
    }

    func keyboardWillHide(_ notification: Notification) {
        mainScrollViewBottomConstraint.constant = 0
    }

編輯:我制作了一個關於我的解決方案的視頻。 https://youtu.be/gS4AKcJAg3Y

最好的方法是,為您的視圖設置一個頂部約束,並在您的 UITextfield 中單擊時使用約束為視圖設置動畫。

@IBOutlet var constraintViewTop: NSLayoutConstraint!

在“textFieldDidBeginEditing”委托中動畫視圖。

func textFieldDidBeginEditing(_ textField: UITextField) {
    switch textField {
    case yourTextfield:
        //This is the code for view up
        UIView.animate(withDuration: 0.45, animations: {
            self. constraintViewTop.constant = -172
        })
    default:
        //This the code for view down
        UIView.animate(withDuration: 0.45, animations: {
            self. constraintViewTop.constant = 0
        })
    }
}

我找到了處理鍵盤重疊問題的最佳方法,只需在靜態表視圖控制器中嵌入(實現)所有視圖和文本字段,系統就會自動向上移動鍵盤。 如果您不喜歡這種方式,請選擇 IQKeyboardManager pod。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM