有花堪折直須折,莫到無花空折枝!<轟隆雉雞>
效果圖:
自定義發送框適應鍵盤彈出
自定義發送框適應鍵盤彈出
分析:
正常情況下底部發送的發送框固定好位置后, 鍵盤彈出會把它擋住!那么就需要我們在鍵盤彈出的時候改變我們發送框工具欄的位置;
思路:
首先: 整體上來看 textView 和 "聲音" "表情" "加號" 三個 Button 添加到一個 View上,然后對 View 進行約束, 這里需要其左邊距離(父視圖View)0,右邊距0, 下面0 然后固定一個高度
其次: 監聽鍵盤的行為當鍵盤彈出來的時候, 我們把發送框所在的 View 底部的約束進行適當的修改,讓其顯示在鍵盤的上方, 鍵盤消失后回到原來位置
代碼實現:
1: 把發送框所在 View 的距離下部的約束拉進響應控制器作為屬性
// 工具條底部約束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolBottomConstraint;
2: 使用系統通話實現監聽鍵盤的行為
#pragma mark 通知監聽鍵盤彈出情況 使用的是系統的通知
#當鍵盤彈出的時候 執行kbWillShow:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
#當鍵盤消失的時候 執行kbHideShow:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbHideShow:) name:UIKeyboardWillHideNotification object:nil];```
3: 實現響應通知的方法
\#pragma mark 鍵盤彈出 觸發事件
```code
# 鍵盤彈出 調整約束的高度
- (void)kbWillShow:(NSNotification *)noti
{
// 獲取鍵盤的高度 首先獲取當前鍵盤的 Rect
CGRect kbFram = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat kbHeight = kbFram.size.height;
// 把約束改掉
self.toolBottomConstraint.constant = kbHeight ;
[UIView animateWithDuration:1 delay:0 options: UIViewAnimationOptionCurveEaseInOut animations:^{
// 布控子視圖
[self.view layoutIfNeeded];
} completion:nil];
}
# 鍵盤收起 一切回到夢開始的地方
- (void)kbHideShow:(NSNotification *)noti
{
// 把約束改成開始的 0
self.toolBottomConstraint.constant = 0 ;
[UIView animateWithDuration:0.1 delay:0 options: UIViewAnimationOptionCurveEaseInOut animations:^{
// 布控子視圖
[self.view layoutIfNeeded];
} completion:nil];
}```
有時間在寫高度適應的問題, 最近寫點小項目! 加油!