Scroll UIScrollView to focused UITextField in Swift

I had a screen with multiple textfields embedded in a scrollview. When a textfield became first responder I wanted the textfield to scroll to the top of the view.

I will explain the way I used to achieve this below, (there probably are other ways, but this way worked for me).
The first thing that was required was to add the UITextFieldDelegate so that we can call the textfield protocol methods.

class ViewController: UITextFieldDelegate

Then I set the delegate of the textfield to self (the viewController that now conforms to UITextFieldDelegate)

let textField = UITextField()
textField.delegate = self

The following method is now available as we conform to UITextFieldDelegate. This will fire any time a text field gains focus.

func textFieldDidBeginEditing(_ textField: UITextField)
    var point = textField.frame.origin
    point.y = point.y - 5
    scrollView.setContentOffset(point, animated: true)

First we find the position of the textfield that now has focus and assign the CGPoint to a variable. We then adjust the y position so that there is some space at the top of the screen when the scrollview scrolls to this position. We then set the contentOffset to the point and set it to animate (to make it look nicer).

Leave a Comment