iOS 键盘遮挡输入 解决办法

时间:2023-03-08 15:34:23
iOS 键盘遮挡输入 解决办法

第一种方式(CGAffineTransform):

通过CGAffineTransformMakeTranslation方法来临时改变位置,然后通过CGAffineTransformIdentity恢复位置;

如果需要加动画,直接放在UIView的animation的block里就可以了。

// 比如这样用
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
self.arrowView.transform = CGAffineTransformIdentity;
}];

第二种方式(UITableView):

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

- (void)viewDidLoad {
[super viewDidLoad];
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];
} .实现通知的响应方法 - (void)boardWillShow:(NSNotification *)sender{
//获得键盘的尺寸
CGRect keyBoardRect=[sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//当键盘将要显示时,将tableView的下边距增跟改为键盘的高度
self.tableView.contentInset = UIEdgeInsetsMake(, , keyBoardRect.size.height, );
} - (void)boardDidHide:(NSNotification *)sender{
//当键盘将要消失时,边距还原初始状态
self.tableView.contentInset = UIEdgeInsetsZero;
}
//测试

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//取消当前输入框的第一响应者
[textField resignFirstResponder];
return YES;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return ;
} - (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(, 0, , 44)];
TF.placeholder = @"请输入";
TF.delegate =self; //文本框添加代理
[cell.contentView addSubview:TF];
cell.textLabel.text = @"测试"; return cell;
}

转载请注明出处:http://ficow.cn

广大喵 Ficow Shen