键盘遮挡输入框的问题

这篇博客介绍了在iOS开发中如何高效地处理键盘弹出遮挡输入框的问题,通过使用键盘通知来实现输入框跟随键盘移动,提高用户体验。文章包含声明、添加通知观察者、响应通知方法以及UITextField代理事件的详细步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iOS开发之时键盘通知之前处理这种问题,总是在触发输入框编辑事件键盘弹出的时候,将当前的View整体向上移动,结束编辑又整体向下移,耗时耗力效率低。


在网上看了使用键盘通知的方法很是方便,所以写了个demo供初学者参考!

1.在ViewController.m文件声明

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)UITableView *tableView;//自定义表格TableView
@end

2.初始化及添加通知观察者

- (void)viewDidLoad {
    [super viewDidLoad]; 4     self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource  = self;
    [self.view addSubview:self.tableView];
    
    //键盘将要显示时候的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardWillShow:) name:UIKeyboardWillShowNotification object:nil];
     //键盘将要结束时候的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

3.实现通知的响应方法

-(void)boardWillShow:(NSNotification *)sender{
    //获得键盘的尺寸
    CGRect keyBoardRect=[sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];                           
    //当键盘将要显示时,将tableView的下边距增跟改为键盘的高度
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}

-(void)boardDidHide:(NSNotification *)sender{
    //当键盘将要消失时,边距还原初始状态
    self.tableView.contentInset = UIEdgeInsetsZero;
}

4.UITextField的代理事件(点击键盘中的return按钮,隐藏键盘)


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    //取消当前输入框的第一响应者
   [textField resignFirstResponder];     
   return YES;
}

5.tableView的代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 15;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ider = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ider];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ider];
    }
    
    UITextField *TF = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, 150, 20)];
    TF.placeholder = @"请输入";
    TF.delegate =self; //文本框添加代理
    [cell.contentView addSubview:TF];
    cell.textLabel.text = @"测试";

    return cell;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值