中二青年逗鍵盤之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,373評論 0 1
  • 概述在iOS開發中UITableView可以說是使用最廣泛的控件,我們平時使用的軟件中到處都可以看到它的影子,類似...
    liudhkk閱讀 9,088評論 3 38
  • 聊天控制器(ChatViewController)界面搭建 14.聊天界面-工具條排版 1)搭建界面 添加聊天控制...
    夜空已沉寂閱讀 3,074評論 0 4
  • 明天要去參加考試了。外面下著雨,就像我的現在的心情,一絲忐忑,一絲惆悵,當然還有那么一絲的自信。 因為這一次我是真...
    yayajy閱讀 160評論 0 0
  • 我的學生告訴我,有自己的目標就要朝著這個目標努力,其實想想這不正是自己平時對他們經常說的嗎! 我的夢,我在心里不停...
    飛流三千閱讀 202評論 0 2