2011-03-23 58 views
2

我會告訴你一個衆所周知的例子whatsapp 當你觸摸文本內的鍵盤彈出,所以我必須移動或移動所有的酒吧和調整視圖的大小一半,所以我仍然可以看到文本那我打字和發送按鈕當顯示iphone的鍵盤時調整UIView,如何?

第1階段: http://www.appbank.net/wp-content/uploads/2010/10/WhatsAppMessenger-18.jpg

第2階段: http://www.onetooneglobal.com/wp-content/uploads/2011/02/onetoone_whatsapp_2.png

什麼是實現這一目標的最佳方式是什麼?

回答

6


#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]; 
} 

試試這個方法。根據您的要求編輯它。

+0

好的,我用你的代碼和它工作,:)我不得不放棄,無效,IBAction並將事件分配給文本,我仍然不知道keyboardWillHide和keyboardWillShow的作用和如何使用它們,..,用於隱藏鍵盤我使用http://stackoverflow.com/questions/2586937/how-to-hide-the-keyboard-programatically-in-iphone。謝謝你的這個精彩的解決方案 – PartySoft 2011-03-29 22:51:50

+0

在某些場景下,如果我們使用textFieldDidBeginEditing和textFieldDidEndEditing,動畫的時間可能並不完美,所以我們可以使用keyboardWillShow和keyboardWillHide來相應地調整時間。這兩種方法提前一點點啓動。反正你的情況,我認爲textFieldDidBeginEditing和textFieldDidEndEditing就足夠了。 :) – 2011-03-30 05:35:40

+0

stayup = YES; 什麼是熬夜嗎? – 2011-09-01 04:44:19

2

你要聽UIKeyboardDidShowNotificationUIKeyboardDidHideNotification,並在對應於您所提供的通知中心將調整你的意見,選擇的方法(通常通過改變UIView.frame屬性)

+0

爲了記錄,Apple有一個很好的教程:https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/ uid/TP40009542-CH5-SW1 – To1ne 2013-08-12 21:12:51

相關問題