在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
网友评论