在viewDidLoad中創建輸入框
//輸入框在屏幕外面
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, MainH, MainW,40)];
textView.backgroundColor = [UIColor redColor];
[self.view addSubview:textView];
self.textView = textView;
然后監聽鍵盤的彈出
//使用NSNotificationCenter鍵盤出現時
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardShown:)
name:UIKeyboardDidShowNotification object:nil];
在cellForRow中創建cell且綁定cell的tag值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *ID = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[UITableViewCell alloc] init];
}
cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 39,[UIScreen mainScreen].bounds.size.width,1)];
view.backgroundColor = [UIColor yellowColor];
[cell.contentView addSubview:view];
return cell;
}
在cell的點擊事件中,獲取cell的高度與坐標,計算此時cell距0的長度,然后彈出鍵盤
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
_y = cell.frame.size.height + cell.frame.origin.y;
[self.textView becomeFirstResponder];
}
此時在鍵盤通知中拿到鍵盤高度,然后計算偏移量
- (void)keyboardShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
//kbSize為鍵盤尺寸
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//鍵盤高度
_kH = kbSize.height;
//改變textView的frame
self.textView.frame = CGRectMake(0, MainH - _kH - 40, MainW, 40);
//計算偏移量,20是狀態欄高度,y其實就是cell底部到textView的y坐標的距離
NSInteger y = ( _y + 20) - (MainH - (_kH + 40));
//偏移量為正數
if (y > 0) {
[self.tableView setContentOffset:CGPointMake(0, y) animated:YES];
}
}
還有其他鍵盤退出,滑動到底部彈出的一些小bug可以根據需要自己改。
注:點擊cell的button彈出思路一樣,修改了一些錯誤。demo地址:https://github.com/buguanhu/KeyboardPop