ios-键盘上移

2017-07-19  本文已影响0人  紫嫣沁

1,两个通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];

2,实现两个方法:

//键盘弹出

-(void)keyboardWillShow:(NSNotification *)n

{

NSDictionary* userInfo = [n userInfo];

//UIKeyboardFrameEndUserInfoKey 要用这个key,别用错啦!!

CGSize keyboardSize =[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;

CGRect frame = self.editAlert.frame;

NSInteger offset = frame.origin.y+frame.size.height - (kScreenHeight - keyboardSize.height);//键盘高度216

NSTimeInterval animationDuration = 0.30f;

[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];

[UIView setAnimationDuration:animationDuration];

if(offset >= 0)

{

self.editAlert.sd_y = kScreenHeight - keyboardSize.height - self.editAlert.sd_height;

}

[UIView commitAnimations];

}

//键盘隐藏

-(void)keyboardWillHide:(NSNotification *)n

{

NSTimeInterval animationDuration = 0.30f;

[UIView beginAnimations:@"ResizeForKeyboard" context:nil];

[UIView setAnimationDuration:animationDuration];

CGRect rect = CGRectMake(58.0f, (kScreenHeight-180)/2, kScreenWidth-58*2, 180);

self.editAlert.frame = rect;

[UIView commitAnimations];

[self.ContentText resignFirstResponder];

_keyboardIsShown= NO;

}

3,记得在dealloc中移除通知:

-(void)dealloc

{

[[NSNotificationCenter defaultCenter]removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.ContentText];

}

上一篇下一篇

猜你喜欢

热点阅读