效果演示:
效果演示.gif
解決的問題:鍵盤(keyboard)彈出時覆蓋了tableViewCell上的輸入框。
關于這個問題最初我是用了系統(tǒng)的UITableViewController類,這個類里系統(tǒng)處理了鍵盤的彈出與輸入框之間的位置關系。But!!!在使用UITabBarController的時候,它計算出的位置關系就會有49高度的誤差。。。至于原因我也沒有找到(雖然知道肯定和tab有關但是真的不知道怎么處理),如果哪位朋友有解決方法的真心求教。。。
既然系統(tǒng)的UITableViewController不會用了,那我就只能自己寫一個自己的TableViewController了。
下面上代碼:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
通過這兩個監(jiān)聽可以得到鍵盤彈出以及收起的時機,然后我們就可以做相應處理了。
- (void)keyboardWillShow:(NSNotification *)notice {
if (self.startContentOffset.y > self.tableView.contentOffset.y) {
self.startContentOffset = self.tableView.contentOffset;
}
NSDictionary *info = [notice userInfo];
CGSize size = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//鍵盤的大小
self.duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];//鍵盤出現(xiàn)的動畫時間
CGFloat keyboardY = [UIScreen mainScreen].bounds.size.height - size.height - 64;//鍵盤的最高點Y值
//currentTextFieldFrame屬性為當前輸入框相對于tableView的frame,在子類中賦值
if ((self.currentTextFieldFrame.origin.y + self.currentTextFieldFrame.size.height - self.startContentOffset.y) > keyboardY) {
[UIView animateWithDuration:self.duration animations:^{
//這里你完全可以再加上一點間隔~
self.tableView.contentOffset = CGPointMake(0, (self.currentTextFieldFrame.origin.y + self.currentTextFieldFrame.size.height) - keyboardY);
}];
}
}
在鍵盤彈出的時候用一個中間量記錄tableView的contentOffset,并比較鍵盤的最高點是否覆蓋在textField上
- (void)keyboardWillHide:(NSNotification *)notice {
[UIView animateWithDuration:self.duration animations:^{
self.tableView.contentOffset = self.startContentOffset;
}];
}
鍵盤收起時還原tableView.contentOffset
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
NSLog(@"Execution dealloc");
}
最后在dealloc的時候移除監(jiān)聽
具體邏輯就是這樣了,下面是我寫的一個demo~
傳送門:毛小崔的github
歡迎各位的回復,有疑問也可以寫出來,當然有更好方案的提出來就更好了~