2011-01-07 33 views
0

我有一個視圖,上面有5個UITextFields。當你點擊文本字段時,彈出鍵盤並覆蓋最下面的兩個文本字段。我調整了代碼點,如果您點擊底部的兩個文本字段之一,視圖將向上滾動,以便文本字段可見。關於通過NSNotification在鍵盤顯示時滾動視圖的問題

我遇到的問題是當您在第一個文本字段中啓動並通過文本字段的標籤時,視圖不會滾動到達最後兩個文本字段。我確定這是因爲在視圖之間切換時,我們的方法keyboardWillShow在我們單擊第一個文本字段後再也不會被再次調用。

我已經嘗試使用textFieldDidBeginEditing方法來確定哪個文本字段現在有焦點,然後我想再次調用我的keyboardWillShow方法。但是,該方法需要NSNotification作爲參數,並且通過我所有的搜索我已經看到,您從不真正想要創建NSNotification對象,而是希望使用NSNotificationCenter中的postNotificationName來傳遞NSNotification對象。我一直無法得到這個工作正常。

這是我的相關代碼。

- (void) viewWillAppear:(BOOL)animated 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window]; 
    [super viewWillAppear:animated]; 
} 

- (void) viewWillDisappear:(BOOL)animated 
{ 
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 
[super viewWillDisappear:animated]; 
} 

- (void) keyboardWillShow: (NSNotification *)notif 
{ 
// get our app delegate so we can access currentTextField 
ScrollingAppDelegate *appDelegate = (ScrollingAppDelegate *)[[UIApplication sharedApplication] delegate]; 
appDelegate.notif = notif; 
NSDictionary *info = [notif userInfo]; 
NSValue *aValue = [info objectForKey: UIKeyboardBoundsUserInfoKey]; 
CGSize keyboardSize = [aValue CGRectValue].size; 
float bottomPoint = (appDelegate.currentTextField.frame.origin.y+ appDelegate.currentTextField.frame.size.height+10); 
scrollAmount = keyboardSize.height - (self.view.frame.size.height - bottomPoint); 
if (scrollAmount > 0) 
{ 
    moveViewUp = YES; 
    [self scrollTheView:YES]; 
} 
else 
{ 
    moveViewUp = NO; 
} 
} 

- (void)scrollTheView: (BOOL)movedUp 
{ 
[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationDuration:0.3]; 
CGRect rect = self.view.frame; 
if (movedUp) 
    { 
    rect.origin.y -= scrollAmount; 
} 
else 
    { 
    rect.origin.y += scrollAmount; 
} 

self.view.frame = rect; 
[UIView commitAnimations]; 
} 


- (void) textFieldDidBeginEditing:(UITextField *)textField 
{ 
// declare app delegate so we can access a varibale in it. 
ScrollingAppDelegate *appDelegate = (ScrollingAppDelegate *)[[UIApplication sharedApplication] delegate]; 

// set the app delegate variable currentTextField to the textField which just got focus so we can access it 
// in our other method keyboardWillShow 
appDelegate.currentTextField = textField; 
    // some how call keyboardWillShow here so the view will scroll to the current text field 
} 

如果我對這個問題有所瞭解,請告訴我。我一直在尋找答案,但到目前爲止還沒有找到答案。我找到的關於滾動視圖的所有內容只能處理一個文本字段,而不是我需要的方式。

感謝

+0

謝謝肖恩,這很好。真的很感激它。 – 2011-01-10 20:47:43

回答

相關問題