[英]Handling keyboard with bottom constraint
我正在使用常規設計和聊天應用程序的UI構建聊天應用程序。
我有我的應用程序需要的“工具欄”(0,0 375x66),我希望它在顯示鍵盤時保持在原位。 它具有4個約束:頂部:0,前導:0,尾部:0,縱橫比:125:22
我有一個UICollectionView
(0,66 375x530),我希望在顯示鍵盤時像其他任何聊天應用一樣進行滾動。 它有4個約束:頂部(至工具欄):0,前導:0,尾部:0,底部(至newMessageView,我將在稍后說明):0
我有一個UIView
里面有一個UITextField
。 我們將其稱為newMessageView
(0,596 375x71),它有4個約束:底部:0,前導:0,尾部:0,長寬比:375:71
現在,我試圖在顯示鍵盤時帶來newMessageView
應用程序。 我正在嘗試這樣:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.newMessageViewBottomConstraint.constant += keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.newMessageViewBottomConstraint.constant -= keyboardSize.height
}
}
}
但完全無法正常工作。 視圖跳躍和隱藏,我真的不明白為什么。
我做對了嗎? 誰能幫助我並指導我嗎?
您必須在更新約束后使用self.view.layoutIfNeeded()
我為您編寫完整的解決方案
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: Notification) {
self.keyboardControl(notification, isShowing: true)
}
@objc func keyboardWillHide(notification: Notification) {
self.keyboardControl(notification, isShowing: false)
}
private func keyboardControl(_ notification: Notification, isShowing: Bool) {
/* Handle the Keyboard property of Default*/
var userInfo = notification.userInfo!
let keyboardRect = (userInfo[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
let curve = (userInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).uint32Value
let convertedFrame = self.view.convert(keyboardRect!, from: nil)
let heightOffset = self.view.bounds.size.height - convertedFrame.origin.y
let options = UIViewAnimationOptions(rawValue: UInt(curve!) << 16 | UIViewAnimationOptions.beginFromCurrentState.rawValue)
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue
var pureheightOffset : CGFloat = -heightOffset
if isShowing { /// Wite space of save area in iphonex ios 11
if #available(iOS 11.0, *) {
pureheightOffset = pureheightOffset + view.safeAreaInsets.bottom
}
}
// Here change you Consrant
// self.actionBarPaddingBottomConstranit?.update(offset:pureheightOffset)
UIView.animate(
withDuration: duration!,
delay: 0,
options: options,
animations: {
self.view.layoutIfNeeded()
},
completion: { bool in
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.