之前也做過類似的功能,但是在Swift
上面的效果不是很好。今天整理了一下之前小項目中的代碼和思路,很好的解決了在登錄界面登錄按鈕被鍵盤遮擋的問題。
先看效果圖
xxoo
如下
注冊鍵盤通知
//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設備上正常運行。