您的位置:首页 > 产品设计 > UI/UE

UITextField,UITextView回收键盘

2016-02-25 17:41 495 查看
有以下几种方式:

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: