前言
相信研究swift/233652.html">swift/81033.html">swift語言的開發者都多多少少了解或者精通Objective—C語言,熟練掌握Objective—C語言的開發者,在學習swift語言的過程中,是比較快速,而又輕松的。本文主要介紹的是關于Swift監聽鍵盤通知及一些處理的相關資料,之前也做過類似的功能,但是在Swift上面的效果不是很好。今天整理了一下之前小項目中的代碼和思路,很好的解決了在登錄界面登錄按鈕被鍵盤遮擋的問題。
先看效果圖
如下
注冊鍵盤通知
//MARK:監聽鍵盤通知 func registerNotification(){ NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_ :)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(_ :)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) }
根據鍵盤通知做出對應的操作
//MARK:鍵盤通知相關操作 @objc func keyBoardWillShow(_ notification:Notification){ DispatchQueue.main.async { /* 每次鍵盤發生變化之前,先恢復原來的狀態 y 是鍵盤布局的origin.y y2 是登錄按鈕的origin.y+height 如果y>y2,登錄按鈕沒有被遮擋,不需要向上移動;反之,按鈕被遮擋,整體需要向上移動一部分 */ self.view.center = CGPoint.init(x: Width/2, y: Height/2) let user_info = notification.userInfo let keyboardRect = (user_info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let y = keyboardRect.origin.y let y2 = (self.nextStep?.frame.origin.y)! + (self.nextStep?.frame.size.height)! + 5 let offset_y = y2 > y ? (y2-y):(0) UIView.animate(withDuration: 0.25, animations: { self.view.center = CGPoint.init(x: Width/2, y: self.view.center.y - offset_y) }) } } @objc func keyBoardWillHide(_ notification:Notification){ DispatchQueue.main.async { self.view.center = CGPoint.init(x: Width/2, y: Height/2) } }
釋放鍵盤通知
因為這里只有這兩個通知,所以我選擇了removeObserver(self)
來移除所有通知,當然,你也可以根據通知名稱來逐個移除。
//MARK:釋放鍵盤監聽通知 func releaseNotification(){ NotificationCenter.default.removeObserver(self) }
經測試,上面的方法在4.0-5.5英寸的iPhone設備上正常運行。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答