Scroll when the keyboard appears — Swift

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

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.

ViewController.swift

--

--

I’m an IOS, Flutter Developer and now a Blogger

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store