#define kOFFSET_FOR_KEYBOARD 280.0
- (void)keyboardWillHide:(NSNotification *)notif {
[self setViewMoveUp:NO];
}
- (void)keyboardWillShow:(NSNotification *)notif{
[self setViewMoveUp:YES];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
stayup = YES;
[self setViewMoveUp:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
stayup = NO;
[self setViewMoveUp:NO];
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMoveUp:(BOOL)moveUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
[UIView setAnimationBeginsFromCurrentState:YES];
CGRect rect = self.view.frame;
if (moveUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
if (rect.origin.y == 0) {
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
//rect.size.height += kOFFSET_FOR_KEYBOARD;
}
}
else
{
if (stayup == NO) {
rect.origin.y += kOFFSET_FOR_KEYBOARD;
//rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
}
self.view.frame = rect;
[UIView commitAnimations];
}
試試這個方法。根據您的要求編輯它。
好的,我用你的代碼和它工作,:)我不得不放棄,無效,IBAction並將事件分配給文本,我仍然不知道keyboardWillHide和keyboardWillShow的作用和如何使用它們,..,用於隱藏鍵盤我使用http://stackoverflow.com/questions/2586937/how-to-hide-the-keyboard-programatically-in-iphone。謝謝你的這個精彩的解決方案 – PartySoft 2011-03-29 22:51:50
在某些場景下,如果我們使用textFieldDidBeginEditing和textFieldDidEndEditing,動畫的時間可能並不完美,所以我們可以使用keyboardWillShow和keyboardWillHide來相應地調整時間。這兩種方法提前一點點啓動。反正你的情況,我認爲textFieldDidBeginEditing和textFieldDidEndEditing就足夠了。 :) – 2011-03-30 05:35:40
stayup = YES; 什麼是熬夜嗎? – 2011-09-01 04:44:19