当键盘存在时,UIViewController向上移动

时间:2014-04-29 04:02:17

标签: objective-c uiviewcontroller

我有一个带文本字段的uiviewcontroller。单击底部文本字段时,键盘会覆盖该字段,当您单击文本字段时,如何使其“向上滚动”。或者只是拥有它以便uiviewcontroller可以滚动

1 个答案:

答案 0 :(得分:0)

尝试将视图的所有文本字段放在滚动视图中,然后使视图控制器符合 UITextFieldDelegate UINavigationControllerDelegate

在viewController.m中定义以下方法

-(IBAction)textFieldDidBeginEditing:(UITextField *)sender // connect all textfields in your view to this method
{
    sender.delegate = self;
}
//called when UIKeyboardDidShowNotification is sent.
-(void)keyboardWasShown:(NSNotification *)aNotification
{
    NSDictionary * info =   [aNotification userInfo];
    CGSize  kbSize  =   [[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
    [self.scrollView setContentOffset:CGPointMake(0, kbSize.height) animated:YES];

}
// Called when the UIKeyboardWillHideNotification is sent,method is called when the keyboard is closed. It returns the scroll view to its original position.
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

//This method is called when you have finished editing a text field.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [textField resignFirstResponder];
}

将它放在viewDidLoad中:

- (void)viewDidLoad
{
    [super viewDidLoad];        
    // Do any additional setup after loading the view.
    self.scrollView.scrollEnabled = YES;
    self.automaticallyAdjustsScrollViewInsets = YES;
}

这可能会成功...... HTH:)