Scroll when the keyboard appears — Swift

Agnel Selvan
3 min readSep 9, 2021

In this blog, we will be looking at how to scroll the screen when the keyboard appears using swift.

Let’s start by creating a new project in XCode.

Open the Main.storyboard and quickly design the layout of the screen

I have just quickly designed the Contact us screen of the application. Make sure to wrap all the views inside the Scroll View.

Now go to Assistant view editor and click on ScrollView in Main.storyboard and press control and Drag it to viewController.swift file. And then add @IBAction function btnClick and link it to Click Me button.

After linking your viewController.swift add the self.view.endEditing(true) on btnClick function this is basically for making keyboard to disappear.

In the viewDidLoad function add the notification observer for keyboard Appear and on keyboard disappear. In the selector create function and pass in the NSNotification. So basically this is for accessing the keyboard height and then declare a variable called isExpand and mention the datatype as bool this variable is used to track whether the keyboard is on or off.

Initially when the TextField is clicked the keyboard will appear and we are getting the keyboard height and then based on the keyboard height we are increasing the height of the scrollView. If we get some error from notification.userInfo then we are increasing the scrollView height as +250 and we are updating the isExpand variable to true.

Similarily when the keyboard disappears we are getting the height of keyboard using UIResponder and we are decreasing the height of scrollView and we are updating the value of isExpand to false.




Agnel Selvan

A person who is learning Flutter Development, Shaders, OpenGL, and Augmented Reality.