View is getting shifted every time I re-tap textfield - ios

so I have a small app where I choose an image, get it into an image view
and I have 2 textfield to insert a funny phrase
(Meme editor app)
my problem is since the bottom textfield is covered when the keyboard is shown I had to shift the view upwards every time the keyboard is shown for the bottom texfield and I succeed in doing that, what goes wrong is that every time I re-tap the beginning or the end of an existing text in the text filed the view shifts up again in undesirable behavior
here is a small GIF that shows what happens exactly
here is my code so far:
Function to get Kyboard height:
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
Function to shift the view up in the condition that bottom textfield is what the user taps
#objc func keyboardWillShow(_ notification:Notification) {
if bottomTextField.isFirstResponder{
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
Function to return the view to its normal position when the user finishes editing the bottom text field
#objc func keyboardWillHide(_ notification:Notification) {
view.frame.origin.y = 0
}
Functions to add and remove observers of keyboard notifications
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
func subscribekeyboardWillHide() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}
func unsubscribekeyboardWillHide() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
and where I call them
override func viewWillAppear(_ animated: Bool) {
super .viewWillAppear(true)
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
subscribeToKeyboardNotifications()
subscribekeyboardWillHide()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
unsubscribekeyboardWillHide()
}
if you could be kind to provide a simple explanation for your solution I would appreciate it

This is what I do while managing keyboard. It causes no problems.
Declare in your UIViewController class
private let notificationCenter = NotificationCenter.default
then in
override func viewDidLoad() {
super.viewDidLoad()
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
This is the adjust for keyboard function
#objc private func adjustForKeyboard(notification: Notification) {
guard let userInfo = notification.userInfo else { return }
guard let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == UIResponder.keyboardWillHideNotification {
scrollView.contentInset = UIEdgeInsets.zero
} else {
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}
scrollView.scrollIndicatorInsets = scrollView.contentInset
}
Deinit here -
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}

Every time you change the cursor location, UIResponder.keyboardWillShowNotification notification triggered, thats why every time you tap the textfield it moves up one keyboard height more.
You can use UIResponder.keyboardDidShowNotification notification instead of UIResponder.keyboardWillShowNotification. This one is not triggered when cursor location changes.

Related

move view up when only keyboard cover textfield

I am trying to build an input screen for the iPhone in swift. The screen has a number of input fields. Most of them on the top of the screen, but three fields are at the bottom. When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen. I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.
for example : I want form txt1 to txt4 the view does not go up.
Is there a way to have the screen only move when the bottom fields are edited?
I have used this code I found here:
override func viewDidLoad() {
txt1.delegate = self
txt2.delegate = self
txt3.delegate = self
txt4.delegate = self
txt5.delegate = self
txt6.delegate = self
txt7.delegate = self
txt8.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
#objc func keyboardWillHide(notification: NSNotification) {
if view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
**
I did this function to start show keyboard while I start editing on textfields:
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
but here it's going for all the textfield that I have and its the same problem.
how can I make it for specific textfield?

Keyboard to show notification not called iOS 12

In my app, I wanted a notification for UIResponder.keyboardWillShowNotification in order to update the y position of my text field. It was working prior to iOS 12; now, it is not called in one of my view controllers (it works for other ones).
Here is my code to do this:
#objc func keyboardWillShow(_ notification: Notification) {
print("keyboard will show 2")
guard let frameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = frameValue.cgRectValue
UIView.animate(withDuration: animationTime) {
self.addViewBottomConstraint.constant = keyboardFrame.size.height
self.view.layoutIfNeeded()
print("Bottom contraint height = \(self.addViewBottomConstraint.constant)")
}
}
#objc func keyboardWillHide(_ notification: Notification) {
UIView.animate(withDuration: animationTime) {
self.addViewBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
Here, "keyboard will show 2" is not printed, but it is printed for other view controllers with the same notifications. Is there anything new in iOS 12 that caused this? Otherwise, is there a particular reason why it is not being called?
This can be related to simulator setup, see menu "Hardware > Keyboard > Connect Keyboard Hardware". If this option is ON, you will get UIKeyboardWillHideNotification, but never UIKeyboardWillShowNotification.

KeyboardWillShow only moves container UIView for certain UITextFields

I have a container UIView that contains a UICollectionView and a UIView, both of which have UITextFields in them. I used NSNotificationCenter to move the container view when the keyboard pops up.
However, it only seems to work for the UICollectionView but not the sub UIView, as shown in the screenshots:
works fine for the text fields in UICollectionView:
but doesn't work for the text field in the UIView:
EDIT: related code:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
kbHeight = keyboardSize.height
self.animateDurationView(true)
}
}
}
func keyboardWillHide(notification: NSNotification) {
self.animateDurationView(false)
}
func animateDurationView(up: Bool) {
var movement = (up ? -kbHeight : kbHeight)
UIView.animateWithDuration(0.3, animations: {
self.durationView.frame = CGRectOffset(self.durationView.frame, 0, movement)
})
}

How to make NSNotificationCenter only run when a certain UITextField is selected

I am using NSNotificationCenter to shift the main view frame up when a keyboard is shown.
However, I only want this to work for when one UITextField is selected.
Here is what I have so far:
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
func keyboardWillShow(notification: NSNotification) {
self.view.frame.origin.y -= getKeyboardHeight(notification)
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y += getKeyboardHeight(notification)
}
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
func unsubscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}
func subscribeToKeyboardHide() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardHide() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
In ViewWillAppear()
self.subscribeToKeyboardNotifications()
self.subscribeToKeyboardHide()
In ViewWillDisappear()
self.unsubscribeToKeyboardNotifications()
self.unsubscribeToKeyboardHide()
How do I make the view shift up when I am only selecting one specific UITextField?
Try this
if yourTextfield.isEditing{}
Or this
if yourTextfield.isFirstResponder{}
To check is this is your textfield
You can create the following extension
extension UIView {
/**
Finds the first responder
:returns: the first responder, or nil if nothing found.
*/
private func findFirstResponder() -> UIView? {
if isFirstResponder() { return self }
else {
for view in subviews as! [UIView] {
if let responder = view.findFirstResponder() {
return responder
}
}
return nil
}
}
}
Then call it like this in your keyboardWillShow
let textField = UIApplication.sharedApplication().keyWindow?.findFirstResponder() as? UITextField
You can now use textField currently active.

Adjust View for keyboard appears when switching UITextField (Swift)

I have two UIView's , the Main one and one which will move up when the keyboard appears (Second UIView has two textfields). I've managed to do this with the following code:
LoginViewController.swift :
override func viewDidLoad() {
super.viewDidLoad()
self.originalCenter = self.contentView.center;
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
}
func keyboardDidShow(notification: NSNotification)
{
UIView.animateWithDuration(1.0, animations: {
self.contentView.center = CGPointMake(self.originalCenter.x, self.originalCenter.y - 40);
})
}
My big problems is that because the movement of the UIView depends on the keyboard notification, when the user taps one TextField it moves up as it should, but when he taps the second one the view moves down automatically. What Im I doing wrong?
This is what is happening: Keyboard Error Gif
This question was answered over here , but I need the solution for Swift language.
Create an instance variable and check whether the keyboard was activated or not:
class ViewController: UIViewController, UITextFieldDelegate {
var _keyboardActivated: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
registerForKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardDidShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillHideNotification,
object: nil)
}
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardWillShow:",
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardWillBeHidden:",
name: UIKeyboardWillHideNotification,
object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if (!_keyboardActivated) {
// do stuff
}
_keyboardActivated = true
}
func keyboardWillBeHidden(notification: NSNotification) {
_keyboardActivated = false
}
}
Set delegate of your textfield and implement the below methods
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
var movementDuration:NSTimeInterval = 0.3
var movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
Reference: http://www.jogendra.com/2015/01/uitextfield-move-up-when-keyboard.html

Resources