有一个320*480的UITextView,点击UITextView的时候,下面的部分会被弹出的软键盘挡住,我们可以将UITextView的高度改为480 - 软键盘的高度,关闭软键盘后,高度恢复为原始高度。

- (void)viewDidLoad
{
[super viewDidLoad];
self.textView = [[UITextView alloc] initWithFrame:self.view.frame];
self.textView.textColor = [UIColor blackColor];
self.textView.font = [UIFont fontWithName:@"Arial" size:18];
self.textView.backgroundColor = [UIColor whiteColor];
self.textView.text = @"This is the text view example, we can edit, delete, add content in the text view.";
self.textView.returnKeyType = UIReturnKeyDefault;
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.scrollEnabled = YES;
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self.view addSubview: self.textView];
[self.textView release];
}

- (void)viewDidUnload
{
[super viewDidUnload];
self.textView = nil;
}

- (void)dealloc {
[textView release], textView = nil;
[super dealloc];
}

- (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)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.size.height -= keyboardRect.size.height;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.size.height += keyboardRect.size.height;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}