一般来说,键盘遮挡主要有这么几种情况,一个是遮住UITextView,还有就是遮住UITextField,一般来说,比较推荐在UIScrollView或者UITableView里加入textfield的控件。但是有时也许难免。。
在UITextView中
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
实现自定义的方法
- (void)keyboardWillShow:(NSNotification *)aNotification
{
NSDictionary *userInfo = [aNotification userInfo];
CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect newFrame = self.view.frame;
newFrame.size.height -= keyboardRect.size.height;
[UIView beginAnimations:@"ResizeTextView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = newFrame;
[UIView commitAnimations];
}获取键盘显示的信息,然后根据信息对view的frame进行调整,然后WillHide方法就跟上面相同,只不过把高度新高度改成+= keyboardRect.size.height就可以了,最后,移除观察者:
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
}在UIView中遮挡UITextField
- (void)keyboardWillShow:(NSNotification *)aNotification
{
NSDictionary *userInfo = [aNotification userInfo];
CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect oldFrame = _viewRect;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y - keyboardRect.size.height + 20, oldFrame.size.width, oldFrame.size.height);
[UIView commitAnimations];
}- (void)keyboardWillHide:(NSNotification *)aNotification
{
NSDictionary *userInfo = [aNotification userInfo];
NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect newFrame = _viewRect;
newFrame.origin.y += 20;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = newFrame;
[UIView commitAnimations];
}UITableView
805



被折叠的 条评论
为什么被折叠?



