中二青年逗键盘之iOS开发调戏tableView

在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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 1,378评论 0 1
  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 9,093评论 3 38
  • 聊天控制器(ChatViewController)界面搭建 14.聊天界面-工具条排版 1)搭建界面 添加聊天控制...
    夜空已沉寂阅读 3,089评论 0 4
  • 明天要去参加考试了。外面下着雨,就像我的现在的心情,一丝忐忑,一丝惆怅,当然还有那么一丝的自信。 因为这一次我是真...
    yayajy阅读 160评论 0 0
  • 我的学生告诉我,有自己的目标就要朝着这个目标努力,其实想想这不正是自己平时对他们经常说的吗! 我的梦,我在心里不停...
    飞流三千阅读 202评论 0 2