Scroll on textField when begin Editing and keyboar

2019-05-24 01:06发布

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?

5条回答
走好不送
2楼-- · 2019-05-24 01:29

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).

查看更多
Animai°情兽
3楼-- · 2019-05-24 01:34

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

查看更多
在下西门庆
4楼-- · 2019-05-24 01:41

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.

查看更多
Ridiculous、
5楼-- · 2019-05-24 01:45

Here are several options that I've used before:

查看更多
登录 后发表回答