Scroll on textField when begin Editing and keyboar

2019-05-24 01:30发布

问题:

I've a viewController composed by an UIImageView that fills the whole view and two textField located at the center of the view. All this is located inside a ScrollView. I use Storyboard and I disabled the autolayout. When I click on a textField, and thus opens the keyboard, I'd like that the scroll is displaced directly on textField. How can I do that?

回答1:

Consider that your TextField outlet is named txtField then implement UITextField Delegate using

txtField.delegate = self;

Considering that your ScrollView outlet is named scrollView. Implement the Textfield Delegate method:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"%@",NSStringFromCGRect(textField.frame));
    [scrollView scrollRectToVisible:textField.frame animated:YES];
}

Hope this helps.

Do let me know if you need more help.



回答2:

I usually use this successfully: http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html



回答3:

Add your controller as an observer of the keyboard notifications. When you receive the notification, resize the scroll view frame and / or set the content offset (depending on the exact effect you want and content size you have).



回答4:

Here are several options that I've used before:

  • Apple's Doco. See the section titled Moving Content That Is Located Under the Keyboard
  • Cocoa With Love article, Sliding UITextFields around to avoid the keyboard
  • If you have several text fields or other form elements in your view, you could alternatively use something like EZForm. It does automatic repositioning of views to keep input fields visible, and also handles input validation and other useful form-related stuff.


回答5:

You can convert the text field coordinate system into Scroll view coordinate system. Use the below code

-(void)rearrangeView{
    // previous

    if (txtActiveField == txtUsername) {
        CGPoint pt;
        CGRect rc = [txtUsername bounds];
        rc = [txtUsername convertRect:rc toView:scrollViewLogin];
        pt = rc.origin;
        pt.x = 0;
        pt.y -= 40;
        [scrollViewLogin setContentOffset:pt animated:YES];
    }
    else if (txtActiveField == txtPassword) {
        // [self.txtEmail becomeFirstResponder];
        CGPoint pt;
        CGRect rc = [txtPassword bounds];
        rc = [txtPassword convertRect:rc toView:scrollViewLogin];
        pt = rc.origin;
        pt.x = 0;
        pt.y -= 40;
        [scrollViewLogin setContentOffset:pt animated:YES];
    }
}

#pragma mark- UITextField Delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    txtActiveField = textField;
    //txtActiveField.placeholder = @"";
    [self rearrangeView];

    return YES;
}

Here txtActiveField is instance variable of type UItextField