2013-02-14 24 views
0

我使用的是UITableView,其中每個單元格都包含UITextField,並且使用Apple官方示例,我希望執行目標,如果它已經隱藏,則將鍵盤上方的活動字段移動。但是,雖然UITableView滾動顯示,但表單不會移動。這裏是我的相關代碼,請幫我指點什麼似乎缺少/錯誤:移動表單內容位於鍵盤下

@interface ViewController(){ 
    UITextField *activeField; 
} 

- (void)viewDidLoad 
{ 
//.... 
    objTableView.scrollEnabled=YES; 

//.... 
} 

#pragma mark - Keyboard notifications 

// Call this method somewhere in your view controller setup code. 
- (void)registerForKeyboardNotifications 

{ 

    [[NSNotificationCenter defaultCenter] addObserver:self 

              selector:@selector(keyboardWasShown:) 

               name:UIKeyboardDidShowNotification object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 

              selector:@selector(keyboardWillBeHidden:) 

               name:UIKeyboardWillHideNotification object:nil]; 

} 
// Called when the UIKeyboardDidShowNotification is sent. 

- (void)keyboardWasShown:(NSNotification*)aNotification 

{ 

    NSDictionary* info = [aNotification userInfo]; 

    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 



    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0); 

    objTableView.contentInset = contentInsets; 

    objTableView.scrollIndicatorInsets = contentInsets; 



    // If active text field is hidden by keyboard, scroll it so it's visible 

    // Your application might not need or want this behavior. 

    CGRect aRect = self.view.frame; 

    aRect.size.height -= kbSize.height; 

    if (!CGRectContainsPoint(aRect, activeField.frame.origin)) { 

     CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height); 

     [objTableView setContentOffset:scrollPoint animated:YES]; 

    } 

} 



// Called when the UIKeyboardWillHideNotification is sent 

- (void)keyboardWillBeHidden:(NSNotification*)aNotification 

{ 

    UIEdgeInsets contentInsets = UIEdgeInsetsZero; 

    objTableView.contentInset = contentInsets; 

    objTableView.scrollIndicatorInsets = contentInsets; 

} 
#pragma mark - UITextFieldDelegate protocol method 

- (void)textFieldDidBeginEditing:(UITextField *)textField 

{ 

    activeField = textField; 

} 
- (void)textFieldDidEndEditing:(UITextField *)textField 

{ 

    activeField = nil; 

} 

回答

0

試試這個代碼:

if (!CGRectContainsPoint(aRect, activeField.frame.origin)) { 
    CGRect rc = [activeField bounds]; 
    rc = [activeField convertRect:rc toView:objTableView]; 
    [objTableView scrollRectToVisible:rc animated:YES]; 
}