最近碰到個問題,UITextField跟隨鍵盤高度做調(diào)整靠益,避免被軟鍵盤遮擋丧肴,理想方法是監(jiān)聽鍵盤彈起和收回的通知來達到效果。在系統(tǒng)自帶的鍵盤中是完全沒有問題的胧后,但在第三方鍵盤(如百度芋浮、搜狗輸入法)居然會觸發(fā)3次 keyboardWillShowNotification
通知,每次的高度居然還不一樣
目前網(wǎng)傳的辦法是只記錄最后一次的高度壳快,本人經(jīng)過多次實驗途样,效果幾乎是很差的。經(jīng)過最后的修改已經(jīng)完美解決這個問題濒憋,特地在此栽樹以備后人乘涼何暇。直接上步驟:
因為我寫的功能是從底部彈出Dialog,同時彈出鍵盤并跟隨鍵盤高度自動變化凛驮,如果你是需要改變VC中的UITextField裆站,參考此代碼稍作修改即可。
var centerY = self.textField.center.y //記錄textField原始的y值
var keyboardHeight:CGFloat = 0.0 //設定一個變量來記錄鍵盤高度
// 監(jiān)聽鍵盤彈出通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(note:)), name:UIResponder.keyboardWillShowNotification,object: nil)
// 監(jiān)聽鍵盤隱藏通知
NotificationCenter.default.addObserver(self,selector: #selector(keyboardHidden(note:)),
name: UIResponder.keyboardWillHideNotification, object: nil)
//鍵盤彈出監(jiān)聽
@objc func keyboardShow(note: Notification) {
guard let userInfo = note.userInfo else {return}
guard let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else{return}
//獲取動畫執(zhí)行的時間
var duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
if duration == nil { duration = 0.25 }
//獲取鍵盤彈起的高度
let keyboardTopYPosition = keyboardRect.height
keyboardHeight = keyboardTopYPosition
UIView.animate(withDuration: duration!, delay: 0, options: .allowAnimatedContent, animations: {
self.textField.center.y = (self.centerY - keyboardTopYPosition)
//這一步是至關(guān)重要的,設置當前textField的y值為原始y值減去鍵盤高度宏胯,由于始終是用原始y值去減羽嫡,所以不管通知幾次都不會錯
}, completion: nil)
}
//鍵盤隱藏監(jiān)聽
@objc func keyboardHidden(note: Notification){
UIView.animate(withDuration: 0.3, delay: 0, options: .allowAnimatedContent, animations: {
self.textField.center.y += self.keyboardHeight
//用當前的y值加上鍵盤高度,最終使得textField回歸原位
}, completion: nil)
}
deinit {
//記得要取消鍵盤通知的監(jiān)聽
NotificationCenter.default.removeObserver(self)
}
我也是Swift初學者肩袍,因為一直都在簡書查閱大佬們的代碼杭棵,希望我記錄的這個文章能夠解決你的問題,目前我使用的版本為Swift5氛赐,測試是沒有任何問題的魂爪,能解決你的問題請給我雙擊評論666