神奇的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)
@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上直接拉怎麼設定?
先去View的Layout Guides>Keyboard 打勾
就會長出Keyboard Layout guide
把TextView.Bottom對齊KeyboardLayoutGuide.Top就完成
然而事情都不這麼簡單就結束...🥹
跑在模擬器上的iOS17.0+iPhone 15 Pro Max
正常運作
同樣的code跑在iOS15.5+iPhone8
出事了🥹textView整個飛掉
因為連TextView都出不來,感覺像是他view起來的時候抓不到或抓錯keyboardGuide的layout
所以我這邊改成一開始先把textView.bottom對準view(safeArea)的bottom,確保他一開始的bottom位置畫對,等viewDidLoad後再改成對準KeyboardLayoutGuide.top(超麻煩)
viewDidload實在改成去對keyboardLayoutGuide
textViewBottom.isActive = false
view.keyboardLayoutGuide.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 50.0).isActive = true
成功!
另外有測試如果純code+iOS15是沒有問題的
只有iOS15+xib需要另外設定😣