#1利用Dummy Api 還原 Instagram part17 輸入欄隨著鍵盤開啟與關閉來自適應高

大家好我是阿喵,好久不見啦各位,因為最近在處理其他case所以比較少寫文章,那廢話不多說我們來看看吧!先附上圖片:

我們先建立鍵盤的監聽事件:

private func keyBoardNotification() {// 開啟鍵盤時觸發的事件
NotificationCenter.default.addObserver(self, selector: #selector(showkeyboard), name: UIResponder.keyboardWillShowNotification, object: nil)
// 關閉鍵盤時觸發的事件
NotificationCenter.default.addObserver(self, selector: #selector(hidekeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
}

再來是建立函數:

回顧上一篇KeyBoardModels是輸入框。

private let keyboardView = KeyBoardModels()

開啟鍵盤函數:

@objc private func showkeyboard(note: Notification) {// 先抓取鍵盤的資訊
let
userInfo = note.userInfo
// 再抓取鍵盤的寬與高
let
keyboard = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size
// 鍵盤開啟時輸入框會往上
keyboardView.transform = CGAffineTransform(translationX: 0, y: -keyboard.height)
// 這邊先給他一個偵測,如果留言數量超過頁面(留言)的高度的話,頁面(留言)會隨者鍵盤高度去做改變,反之不變。
guard
tableView.contentSize.height >= tableView.height else {
return}// 改變頁面(留言)高度
tableView.transform = CGAffineTransform(translationX: 0, y: -keyboard.height)
tableView.scrollToRow(at: IndexPath(row: 0, section: 1), at: .bottom, animated: true)}

關閉鍵盤函數:

@objc private func hidekeyboard(note: Notification) {// 回到原本的位置
keyboardView.transform = .identity
// 更新UI元件
keyboardView.layoutIfNeeded()
tableView.transform = .identitytableView.layoutSubviews()}

這樣就可以自動伸縮數入欄的高度了,感謝各位收看!

參考資料:

上一篇文章:

下一篇文章:

--

--