Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScrollView and keyboard in Swift

I started creating a simple iOS app that does some operations.

But I'm having some problems when the keyboard appears, hiding one of my textfields.

I think it's a common problem and I did some research but I couldn't find anything that solved my problem.

I want to use a ScrollView rather than animate the textfield to make it visible.

like image 873
GalinhaVoadora Avatar asked Nov 01 '14 12:11

GalinhaVoadora


People also ask

How do I scroll up when keyboard appears in IOS?

There are two things to do in keyboardWasShown to scroll the text view. First, set the text view's content inset so the bottom edge is the keyboard's height. Second, set the scroll indicator insets to the text view's content inset.

What is Scrollview in Swift?

Overview. UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView . A scroll view is a view with an origin that's adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the app's main window.

How do I move view up when keyboard appears in IOS SwiftUI?

Moving SwiftUI View Up When Keyboard AppearsCreate keyboard height state. SwiftUI will automatically update the view whenever the keyboard height changes. Add padding to the bottom of the view, which will make it move up and down with the keyboard.


1 Answers

In ViewDidLoad, register the notifications:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil) 

Add below observer methods which does the automatic scrolling when keyboard appears.

@objc func keyboardWillShow(notification:NSNotification) {      guard let userInfo = notification.userInfo else { return }     var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue     keyboardFrame = self.view.convert(keyboardFrame, from: nil)      var contentInset:UIEdgeInsets = self.scrollView.contentInset     contentInset.bottom = keyboardFrame.size.height + 20     scrollView.contentInset = contentInset }  @objc func keyboardWillHide(notification:NSNotification) {      let contentInset:UIEdgeInsets = UIEdgeInsets.zero     scrollView.contentInset = contentInset } 
like image 52
Sudheer Kumar Palchuri Avatar answered Oct 01 '22 19:10

Sudheer Kumar Palchuri