2024-09-06|閱讀時間 ‧ 約 22 分鐘

iOS15的鍵盤佈局問題與解決方案

神奇的iOS15+xib/storyboard的bug

iOS15新出了一個UIKeyboardLayout Guide,簡化原本很複雜的鍵盤升降推元件。
Before
1.先去註冊鍵盤升降的通知事件

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  1. 去調整元件的autolayout
@objc 
private func keyboardWillShow(notification: NSNotification) {
  if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
      textViewBottomConstraint.constant = keyboardSize.height - buttonViewHeightConstraint.constant
    }
}
    
@objc
private func keyboardWillHide(notification: NSNotification) {
   textViewBottomConstraint.constant = 10
}


3. 保持好習慣,離開controller前要註銷通知

 NotificationCenter.default.removeObserver(self)

總共要三個步驟很累🛌

After
元件的bottomAnchor去對KeyboardLayoutGuide.topAnchor

 textView.bottomAnchor.constraint(equalTo: self.view.keyboardLayoutGuide.topAnchor, constant: -60.0).isActive = true

搭拉!結束✨



設定Xib

如果想要在Xib上直接拉怎麼設定?

先去View的Layout Guides>Keyboard 打勾


就會長出Keyboard Layout guide

把TextView.Bottom對齊KeyboardLayoutGuide.Top就完成


然而事情都不這麼簡單就結束...🥹

跑在模擬器上的iOS17.0+iPhone 15 Pro Max

正常運作


iOS17鍵盤升降


同樣的code跑在iOS15.5+iPhone8

出事了🥹textView整個飛掉

ios15.5

因為連TextView都出不來,感覺像是他view起來的時候抓不到或抓錯keyboardGuide的layout

所以我這邊改成一開始先把textView.bottom對準view(safeArea)的bottom,確保他一開始的bottom位置畫對,等viewDidLoad後再改成對準KeyboardLayoutGuide.top(超麻煩)

TextView先對Safe Area的bottom

viewDidload實在改成去對keyboardLayoutGuide

textViewBottom.isActive = false

view.keyboardLayoutGuide.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 50.0).isActive = true


成功!


ios15


另外有測試如果純code+iOS15是沒有問題的

只有iOS15+xib需要另外設定😣





分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.