Customize automatic UIScrollView scrolling with UITextField - ios

I would like to customize the scroll-offset when showing the keyboard. As you can see in the GIF, the Textfields are quite close to the keyboard and I would like to have a custom position. The "Name" textfield should have 50px more distance and the "Loan Title" textfield should just scroll to the bottom of my UIScrollView.
To be able to scroll past the keyboard I'm changing the UIScrollView insets. Strangely iOS automatically scrolls to the firstResponder textfield (see GIF).
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
#objc func keyboardWillShow(notification: NSNotification) {
// get the Keyboard size
let userInfo = notification.userInfo!
let keyboardEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
// update edge insets for scrollview
self.mainScrollView.scrollIndicatorInsets.bottom = keyboardEndFrame.height - self.view.layoutMargins.bottom
self.mainScrollView.contentInset.bottom = keyboardEndFrame.height - self.view.layoutMargins.bottom
}
I already tried to use the UITextfieldDelegate method: textFieldDidBeginEditing(_ textField: UITextField)
I also tried to use the Apple way described here: https://stackoverflow.com/a/28813720/7421005
None of these ways let me customize the automatic scroll position. In fact it kind of overrides every attempt. Does anyone know a way to workaround this?

You can prevent your view controller from automatically scrolling by setting automaticallyAdjustsScrollviewInsets to false as described here.
Implementing keyboard avoidance is also pretty straight forward. You can see how to do it here.
I don't believe there is any way to keep the automatic positioning and apply your own custom offset. You could experiment with making text field contained in another larger view and making that larger view the first responder, but that would be a hack at best.

I found a solution by myself. The problem was that the automatic scroll (animation) was interfering with my scrollRectToVisible call. Putting this in async fixed the problem.
It now looks similar to this:
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
#objc func keyboardWillShow(notification: NSNotification) {
// get the Keyboard size
let userInfo = notification.userInfo!
let keyboardEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
// update edge insets for scrollview
self.mainScrollView.scrollIndicatorInsets.bottom = keyboardEndFrame.height - self.view.layoutMargins.bottom
self.mainScrollView.contentInset.bottom = keyboardEndFrame.height - self.view.layoutMargins.bottom
var frame = CGRect.zero
if nameTextField.isFirstResponder {
frame = CGRect(x: nameTextField.frame.origin.x, y: nameTextField.frame.origin.y + 50, width: nameTextField.frame.size.width, height: nameTextField.frame.size.height)
}
if titleTextField.isFirstResponder {
frame = CGRect(x: titleTextField.frame.origin.x, y: titleTextField.frame.origin.y + titleShortcutsCollectionView.frame.height + 25, width: titleTextField.frame.size.width, height: titleTextField.frame.size.height)
}
DispatchQueue.main.async {
self.mainScrollView.scrollRectToVisible(frame, animated: true)
}
}

Related

How to darken/tint background when user clicks UITextView and keyboard appears?

Currently, I am able to make my keyboard appear/hide when I click inside/outside my UITextView. I'd like to make this nicer by tinting the background darker when keyboard appears, and then have the background return to normal when keyboard goes away.
I was told this behavior might be called "Focus" or "Modal Shadow Overlay" but have been unable to find a tutorial or images that match my goal. Here is a screenshot that shows exactly what I want to accomplish: when writing a caption for a new Instagram post, the background tints darker.
How do I implement this behavior in Swift?
What's this behavior called in iOS programming?
Thank you. [:
First of all to answer your two questions :
There are many ways to implement the overlay.
You can add a UIView as a subview, giving it constraints as vertical spacing from textView and aligning the bottom of the self.view and change its alpha when keyboard is presented/dismissed.
You can add a MaskView to self.view of a viewcontroller. The problem would be that when a mask is applied it turns all the other area black(Of course you can change color) and only the part that you set in the mask frame will be the color(black with 0.5 alpha) that you suggested.
You can call it adding an overlay(there isn't something else other than adding a mask from Apple's documentation that I've come across)
Now coming to the approach I've been using for a long time.
I add a UIView called overlay variable to my ViewController, Currently setting its frame to CGRect.zero
var overlay: UIView = UIView(frame: CGRect.zero)
After that, I add the Notification Observers for keyboardWillShow and keyboardWillHide in viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
And add the corresponding selectors to handle the Notifications
#objc func keyboardWillShow(notification: NSNotification)
#objc func keyboardWillHide(notification: NSNotification)
In keyboardWillShow, I get the keyboard frame to get the keyboard height
After that, I calculate the height of the overlay by getting the height of the screen and subtracting the navigation bar height, height of the textView and any margin added to the top of textView
Then I initialize my overlay variable by giving it the Y Position of from just below the textView. Initially, I set it's color to be UIColor.clear Add it as a subView to self.view and then changing it's color to black with 0.5 alpha with a 0.5 duration animation.
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let overlayHeight = UIScreen.main.bounds.height - heightOfNavigationBar - keyboardSize.height - textView.frame.size.height - topConstraintofTextView(if any)
let overlayFrame = CGRect(x: 0, y: textView.frame.size.height + textView.frame.origin.y, width: UIScreen.main.bounds.width, height: overlayHeight)
self.overlay = UIView(frame: overlayFrame)
self.overlay.backgroundColor = .clear
self.view.addSubview(overlay)
UIView.animate(withDuration: 0.5, animations: {
self.overlay.backgroundColor = UIColor.black.withAlphaComponent(0.5)
})
}
}
After that, In keyboardWillHide, I change the alpha of overlay to be 0 with a little animation and as soon as it ends I remove the Overlay from superView.
#objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.5, animations: {
self.overlay.backgroundColor = UIColor.black.withAlphaComponent(0)
}, completion: { (completed) in
self.overlay.removeFromSuperview()
})
self.overlay.removeFromSuperview()
}
And I do self.view.endEditing(true) in touchesBegan of viewController to dismiss the keyboard but that's upto you how you want to dismiss it.
Here's how it looks
Hope it helps!

Swift 3 : Issue with cursor of textView when touched by the user

I've been struggling with a rather stupid issue for a few days now and I have not been able to find a solution.
I have a view controller with the following hierarchy: xcode screenshot
The user will have the possibility to add pictures below the textView (I haven't implemented this feature yet).
I set the "scrolling enabled" property of my textView to false so that its height automatically increases or decreases depending on the content typed by the user, which is working as expected.
I use the notification center in order to change the scrollView's contentInsets when the keyboard is shown like so:
func keyboardWillShow(notification: NSNotification) {
var userInfo = notification.userInfo!
var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInsets: UIEdgeInsets = self.scrollView.contentInset
contentInsets.bottom = keyboardFrame.size.height + 3*self.postContentTextView.font!.lineHeight
self.scrollView.contentInset = contentInsets
}
func keyboardWillHide(notification: NSNotification) {
let contentInsets = UIEdgeInsets.zero
self.scrollView.contentInset = contentInsets
}
with the following observers in viewDidLoad:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
I also set the scroll view content size in the viewDidLayoutSubviews function:
override func viewDidLayoutSubviews() {
self.scrollView.contentSize = self.postContentTextView.frame.size
}
Everything seemed to work fine until I realize that when the text is "too long" (or maybe it is something else), I am not able to select the last lines of the textView when I touch them. Actually, when I touch the screen the cursor is supposed to appear on the line I have just touched. This works normally for three quarters of the textView but it looks like the textView does not detect my finger for the last lines (the bigger the height is, the worse this issue is).
At the beginning, I thought I had a problem with my screen but I tested it on the iOS Simulator and the same problem occurred.
I have to admit that I am completely clueless about it. Does any of you have an idea of what the problem could be ?
Have you checked its constraints? The UITextView might be outside the bounds of its superviews. Set clipsToBounds to superview & test it. If it is out of the superview bounds, it will not detect touch

UITextView - Scrolling to selected place

I have a Notes view controller with a large UITextView in it. When the keyboard is active, I've made sure the contentInset is adjusted so that the user can see what's being typed. This works well.
However, if the textView already has a large amount of text in it and the keyboard isn't active yet, when the user taps on text in the lower portion of the textView, the textView doesn't automatically scroll up to show their cursor. As soon as they start typing, the textView scrolls to the appropriate position, but I'd like the textView to scroll to the position of the cursor as soon as they tap in the textView.
Here's my code:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWasShown(_ notification: Notification) {
let mainViewY = self.view.frame.origin.y
let textViewY = self.textView.frame.origin.y
let oneLineHeight = self.textView.font.lineHeight
let delta = (textViewY - mainViewY) - oneLineHeight
let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
let keyboardHeight = (keyboardSize?.height)!
self.textView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight + delta, 0)
self.textView.scrollIndicatorInsets = textView.contentInset
}
func keyboardWillBeHidden(_ notification: Notification) {
self.textView.contentInset = UIEdgeInsets.zero
self.textView.scrollIndicatorInsets = UIEdgeInsets.zero
}
I searched for people asking this question but couldn't find anyone experiencing my particular issue.
How can I ensure that when the user taps the textView to begin typing in a portion of the textView that would be covered by the keyboard, the textView scrolls to show their cursor even before they actually type?
You can achieve this by calling scrollRangeToVisible (docs here) using the text view's selectedRange. That method scrolls the text view to any range of text, and the selectedRange should be at the position of the cursor.
I was having a similar issue, but I tried out your sample code.
In viewDidLoad, I commented out the second observer (self.keyboardWillBeHidden).
When I ran the simulator and selected any part of a large block of text, the textView did automatically scroll to the correct position.

how can I move my container up when user displays a screen keyboard in swift?

I have a UIViewController with two containers embedded and one textfield. So far when user taps the textfield the whole screen moves up so the keyboard can fit without covering the lower part of the containers.
This is how it looks in my story board:
My code looks as follows:
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
// view.addGestureRecognizer(tap)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
if(isKeyboardShown == false){
realKeyboardSize = CGRect(x: keyboardSize.origin.x, y: keyboardSize.origin.y, width: keyboardSize.width, height: keyboardSize.height)
isKeyboardShown = true
self.view.frame.origin.y -= realKeyboardSize!.height
}else{
isKeyboardShown = false
self.view.frame.origin.y += realKeyboardSize!.height
}
}
}
Is it possible to move the lower container up instead of the whole screen?
I imagine it working like this:
topContainer stays untouched, lowerContainer moves up so that half of it is hidden behind topContainer and the keyboard is visible. When user hides the keyboard everything comes back to normal.
If you are using autolayout, you can achieve this by changing bottom constraint runtime
Here is your hierarchy and related constraints..
For how it works and how to setup things check this link
and Here is the demo, if you don't understand
take outlet of container's bottom constraint and increase it's constant to keyboard size or take outlet of top constraint and decrease it's constant to keyboard size . hope this will help :)

UIScrollView doesn't move the view properly when the keyboard appears

I have a view controller with a UIScrollView pinned to all 4 sides. Then a UIView inside with all its 4 sides pinned to the scroll view and as well as equal width and equal height constraints added.
Inside this view, there are two container views. These two container views embed two separate UITableViewControllers. I'm getting no auto layout errors or warnings.
This is how it looks when it's run.
In the bottom table view, one cell(middle one of the first section) has a UITextField and the bottom cell has a UITextView. So obviously when the keyboard appears, these fields get obscured.
So what I wanted to do was to move the entire view that contains both container views when the keyboard appears. That's why I embedded it inside a scrollview. I use this code to monitor keyboard showing/hiding and set the scrollview's content inset accordingly.
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillShow(notification: NSNotification) {
adjustInsetForKeyboard(true, notification: notification)
}
func keyboardWillHide(notification: NSNotification) {
adjustInsetForKeyboard(false, notification: notification)
}
func adjustInsetForKeyboard(show: Bool, notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
let keybaordFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keybaordFrame)) * (show ? 1 : -1)
scrollView.contentInset.bottom += adjustmentHeight
}
}
But there are a couple of issues.
When the keyboard appears and although I change the scrollview's content inset, the entire view doesn't move. It does this weird thing. The bottom tableview goes under the top table view. It's easier to show so here is a video.
Tableviews overlapping issue
When I refocus on a textfield for more than 1 time, the scrollview goes off the screen!
Tableview going off the screen
Anyone got an idea why this is happening?
Dropbox link to demo project
A UITableViewController already automatically handles the adjustment of the content inset when the keyboard is shown. There is no documented way to disable this behaviour. You can override viewWillAppear(animated: Bool) in your StaticTableViewController and not call it's super method:
override func viewWillAppear(animated: Bool) {
}
It's probably where the UITableViewController registers for the keyboard events, as this disables the content inset adjustment. However, I can't tell you if there will be other adverse effects of not calling viewWillAppear of UITableViewController and this behaviour might change with future versions of iOS. So a safer way is to just not use UITableViewController and add a standard UITableView to a UIViewController and load your cells in there.
Also note that with your design the user could scroll all the way up and hide your lower content view behind the keyboard. Then the user can't scroll down as any scrolling only scrolls and bounces the upper tableview. So rethink your design or hide the keyboard as soon as the user scrolls
There are couple ways:
To observe UIKeyboadWillShowNotification and UIKeyboardWillHideNotification, get keyboard size data from it and adjust your scrollView contentInset bottom value properly.
func viewDidAppear() {
super.viewDidAppear()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "increaseContentInset:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "decreaseContentInset:", name: UIKeyboardWillHideNotification, object: nil)
}
func viewDidDisappear(){
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func increaseContentInset(notification: NSNotification) {
let endRect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]
scrollView.contentInset = UIEdgeInsetsMake(0, 0, CGRectGetHeight(endRect), 0)
}
func decreaseContentInset(notification: NSNotification) {
scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
Use the library for it. I strongly recommend you to use TPKeyboardAvoiding

Resources