UITextField,UITextView回收键盘

本文介绍了三种在iOS应用中优化键盘回收的方案,包括滚动时自动回收键盘、通过Return按键回收、以及点击TableView空白处回收键盘。同时,提供了解决在键盘显示时避免第一个输入框滚动的代码实现。

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

有以下几种方式:
1、滚动时回收键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
for (int index = 0; index < 6; index ++) {
UITextField *textField = [_Table viewWithTag:20+index];
[textField resignFirstResponder];
}
}
2、Return时回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
3、点击UITableView空白处回收键盘
使键盘出来时点击任意地方回收键盘,此方法要在加载视图之前调用,否则项目会奔溃,
- (void)setUpForDismissKeyboard {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
UITapGestureRecognizer *singleTapGR =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tapAnywhereToDismissKeyboard:)];
NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
[nc addObserverForName:UIKeyboardWillShowNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[self.view addGestureRecognizer:singleTapGR];
}];
[nc addObserverForName:UIKeyboardWillHideNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[self.view removeGestureRecognizer:singleTapGR];
}];
}
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
//此method会将self.view里所有的subview的first responder都resign掉
[self.view endEditing:YES];
}

回收键盘和显示键盘是UITableView一起滚动检测,在此如果要是第一个的话一起会滚动,导致第一个输入情况看不到,如果要是大牛知道的,请告知;如何在通知里面判断除了第一个其他的才滚动,第一个不用滚动:谢谢:代码如下:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
-(void)keyboardWillDisappear:(NSNotification *)notification
{
CGRect currentFrame = self.Table.frame;
CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
currentFrame.origin.y = currentFrame.origin.y + change ;
self.Table.frame = currentFrame;
}
-(void)keyboardWillAppear:(NSNotification *)notification
{
CGRect currentFrame = self.Table.frame;
CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
currentFrame.origin.y = currentFrame.origin.y - change ;
self.Table.frame = currentFrame;

}
//计算键盘的高度
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo
{
// [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:self];
CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil];
return keyboardEndingFrame.size.height;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值