Adam Strait
Adam Strait

Reputation: 365

scrollview content returns to original position when textfield resigns first responder

New iOS developer with first commissioned app.

Have scrollview with multiple text fields.

Have coded upward movement of page content in textFieldDidBeginEditing: so that text fields are not obscured by keyboard. Have coded keyboard to disappear when keyboard return key pressed using textFieldShouldReturn: and I have coded for the screen to return to its original position in didHideKeyboard.

if a user taps outside of the first responder text field (including if they tap in another text field) somehow the screen returns to its original position without any of my code being fired, and without the keyboard disappearing. I am not using autolayout.

My question is how can I prevent the screen from returning to its original position when a user taps a second text field immediately after typing in the first text field?

Upvotes: 2

Views: 1170

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130193

It depends on what you want to do when the user tries to touch outside the text field. One option would be to simply disable scrolling on the scroll view while the text field is editing, and then re-enabling it upon dismissal of the keyboard.

A different option would be to implement the UIScrollViewDelegate method scrollViewWillBeginDragging: to detect the user is moving the scroll view, and then reseting the scrollview's offset, and resigning first responder from the text field from there.

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (myTextField.isFirstResponder) {
        [scrollView setContentOffset:originalOffset];
        [myTextField resignFirstResponder];
    }
}

Upvotes: 2

Rahul Patel
Rahul Patel

Reputation: 5886

For Your issue, You can get batter library named TPKeyboardAvoiding to set scroll position with UITextField and UITextView with keyboard open and hide. You dont need any manual setting of scroll postion in diffrent methods.
It is subclass of UIScrollView. And its manage all stuff.
Please get files and implementation details on Keyboard Avoiding Scrollview

Upvotes: 0

Related Questions