Move subview up when keyboard displayed over textfields in subview - swift

I have two textfields inside a subview and i am trying to move subview up when any of textfield clicked inside subview and keyboard appears. The problem is subview moves down when subview is up and i clicked on second textfield. It should hide when I touch any of the view except textfields.
The definition of my two textfield and subview;
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var loginView: UIView!
The code in viewDidLoad
NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillHide), name: .UIKeyboardWillShow, object: nil)
And two other functions which show and hide keyboard
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if loginView.frame.origin.y == 0{
let height = keyboardSize.height
self.loginView.frame.origin.y += height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if loginView.frame.origin.y != 0 {
let height = keyboardSize.height
self.loginView.frame.origin.y -= height
}
}
}
I would like to know how can I avoid subview down when I click textfield while subview is up.

Just make the y-origin of view to zero when keyboard is down.
When you tap the other textField while keyboard is open this is .
func keyboardWillHide(notification: NSNotification) {
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if loginView.frame.origin.y == 0{
let height = keyboardSize.height
self.loginView.frame.origin.y = -height
}
}
}
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if loginView.frame.origin.y != 0 {
let height = keyboardSize.height
self.loginView.frame.origin.y = 0
}
}
}

Related

Move textfield up when it is not visible

I want to move textfield up when keyword covers the textfield. Now I am facing a problem with the moving textfield up: it moves up but every time when I click one of the textfields.
How to move the textfield up only when it is covered by keyword?
Also, I have scrolling when the textfield tapped, but it does not work correctly
Here is my code:
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)
self.hideKeyboardWhenTappedAround()
}
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
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
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
Simply use this cocoapods to manage all text fields
pod 'IQKeyboardManagerSwift'
Install pods in your project
Add the below line in your AppDelegate file under the didFinishLaunchingWithOptions method
IQKeyboardManager.shared.enable = true
Here is a reference link -- IQKeyboardManagerSwift
Solutions.
First way you can listen keyboardWillChangeFrameNotification
Second way you can hide keywords textField.autocorrectionType = .no

iOS keyboard hides a UITextField

When I press on a UITextField that is on the lower part of the screen, it is hidden by the keyboard.
What I wanted to do is moving up the view, with the standard iOS animation, reaching the UITextField that in which I am inserting some text.
I am developing the app in Swift 5 (Xcode 10.2)
The result that I have reached is that now I can move the view (a little earlier than desired) but the view moves every time I press on a UITextField, not only the one that will be hided by the keyboard.
class ViewController: UIViewController {
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
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)
}
#objc func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo else {
return
}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = keyboardSize.cgRectValue
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardFrame.height
}
}
#objc func keyboardWillHide(notification: NSNotification) {
guard let userInfo = notification.userInfo else {
return
}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = keyboardSize.cgRectValue
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardFrame.height
}
}
}
The result that I want to obtain is that if the user presses on a UITextField that will be hided by the keyboard, then, a little bit after the keyboard appeared, the view is moved up until the user can see the UITextField that has pressed.
I've searched a long for a solution to this problem but all others that I've seen seems outdated or not doing what I'm trying to achieve.
you can try by taking scrollview :
import UIKit
class ViewController: UIViewController {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self,selector:#selector(self.keyboardWillShow),name:UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillHide),name:UIResponder.keyboardDidHideNotification, object: nil)
}
#objc func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo,
let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else{
return
}
let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frame.height, right: 0)
scrollView.contentInset = contentInset
}
#objc func keyboardWillHide(notification: Notification)
{
scrollView.contentInset = UIEdgeInsets.zero
}
}

Keyboard height observer gives inacurate height

I'm using the observer below to determine my keyboard height.
I then use this keyboardHeight to adjust the bottom constraint for a UIView (image attached):
#IBOutlet weak var postViewBottomContraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
and the method:
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
keyboardHeight = keyboardSize.height
print("Keyboard Height is:",keyboardHeight)
}
}
, and here is where I change the height:
func startEditing() {
UIView.animate(withDuration: 0.5) {
self.postViewBottomContraint.constant = self.keyboardHeight
print ("Bottom constraint is:",self.postViewBottomContraint.constant.description)
self.postTextView.textColor = UIColor.lightGray
self.view.layoutIfNeeded()
}
}
It adds a space between the keyboard and the UIView even though the keyboardHeight and the bottomConstraint are identical (in my case it is 253.0), is it adding something extra that is not visible or is there something else going on?

Swift Scroll to UITextField via UiscrollView only acts first time bug

im posting my full code here. the problem is when initially loading the app and the viewcontroller. it fully works. tap on the two textfields and the scrollview pushes up and keyboard is below the current textfield. but then if tapping out of the text field.. moving the the view up and retaping on the textfield it doesnt do it anymore. Also, if going back via nav controller and then loading again this viewcontroller, it wont do anything. it doesnt scroll anymore..( doesnt push the textfield up and keyboard goes below it anymore ) ...
import UIKit
import Parse
import Alamofire
import SwiftyJSON
class VCreservacion: UIViewController,UITextFieldDelegate,UIScrollViewDelegate {
var SUCURSALID = 0
var EMP_NOMBRE = ""
var DIRECCION = ""
var PROVINCIA = ""
var RESTID = 20556
#IBOutlet var lbl_empresa: UILabel!
#IBOutlet var lbl_direccion: UILabel!
#IBOutlet var lbl_step: UILabel!
#IBOutlet var cantidadView: UIView!
#IBOutlet var datePicker: UIDatePicker!
#IBOutlet var btn_reservar: UIButton!
#IBOutlet var stackView: UIStackView!
#IBOutlet var scrollView: UIScrollView!
#IBOutlet var txtComentario: UITextField!
#IBOutlet weak var txtCelular: UITextField!
var activeField: UITextField?
var steps = 2
// MARK: RESERVE ACTION
#IBAction func ReserveAction(_ sender: UIButton) {
print("Reservando...")
// For date formater
var dateformated = ""
var dateformated2 = ""
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
dateformated = formatter.string(from: datePicker.clampedDate)
dateformated2 = formatter.string(from: datePicker.date)
print(dateformated)
print(dateformated2)
let cart = Cart.sharedInstance
guard let user = PFUser.current() else {
cart.showAlertView("Login", message: "Debes estar logeado para poder reservar.")
return
}
Alamofire.request("URL String", parameters: ["qty": "\(steps)","sucursalid":"\(self.SUCURSALID)","restid":"\(RESTID)","comment":"\(txtComentario.text!)","phone":"\(txtCelular.text!)","datetime":"\(dateformated)","action":"request","userid":"\(user.objectId!)"]).authenticate(usingCredential: cart.credential).responseJSON() {
response in
if (response.error != nil ) {
print(response.error.debugDescription)
print(response.request)
cart.showAlertView("Error", message: "there was an error.")
}
if(response.result.value != nil) {
let json = JSON(response.result.value!);
print(json);
let success:Bool = json["success"].boolValue
let error: Bool = json["error"].boolValue
if(success) {
print("con exito")
let alert = UIAlertController(title: "Reserva Enviada", message: "Tu reserva ha sido enviada y serĂ¡ revisada por el establecimiento", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
// Get the previous Controller.
let targetController: UIViewController = (self.navigationController?.viewControllers[self.navigationController!.viewControllers.count - 3])!
// And go to that Controller
self.navigationController?.popToViewController(targetController, animated: true)
}
alert.addAction(okAction)
self.present(alert,animated:true)
}
}
}
}
#IBAction func stepperValue(_ sender: UIStepper) {
self.lbl_step.text = Int(sender.value).description
steps = Int(sender.value)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerForKeyboardNotifications()
self.scrollView.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
deregisterFromKeyboardNotifications()
self.scrollView.delegate = nil
}
// MARK: Viewdidload
override func viewDidLoad() {
super.viewDidLoad()
// enable scroll on scrollview
self.scrollView.isScrollEnabled = true
// step label initial value 2
self.lbl_step.text = "2"
// Get celular or phone
if ( Cart.sharedInstance.User_celular != "") {
txtCelular.text = Cart.sharedInstance.User_celular
} else {
txtCelular.text = Cart.sharedInstance.User_phone
}
let nearesthour = Date().nearestHour()
self.datePicker.minimumDate = nearesthour
self.txtComentario.delegate = self
self.txtCelular.delegate = self
self.txtCelular.tag = 20
self.scrollView.delegate = self
// tap gesture recognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
self.scrollView.addGestureRecognizer(tap)
print("el enarest hour es \(nearesthour as Date?) y el date normal es \(Date())")
self.btn_reservar.layer.cornerRadius = 10
self.cantidadView.layer.cornerRadius = 10
self.lbl_empresa.text = EMP_NOMBRE
self.lbl_direccion.text = DIRECCION
/*
print("VC Reservacion")
print("SUCURSAL \(SUCURSALID) ")
print("EMP NOMBRE " + EMP_NOMBRE)
print("DIRECCION " + DIRECCION)
*/
}
// MARK: TEXTFIELD STUFF
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.activeField = textField
return true
}
/*
func textFieldDidBeginEditing(_ textField: UITextField) {
self.activeField = textField
}
*/
func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
}
func registerForKeyboardNotifications(){
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterFromKeyboardNotifications(){
//Removing notifies on keyboard appearing
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
#objc func keyboardWasShown(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
print(" Keyboaard shown")
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
print(" el keyboardsize is \(keyboardSize)")
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height + 80, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
print("VIEW COMPLETE FRAME IS \(aRect)")
print("KEYBOARD FRAME HEIGHT \(keyboardSize!.height)")
aRect.size.height -= keyboardSize!.height
print("FRAME MENOS KEYBOARD ES \(aRect)")
print("SCROLLVIEW CONTENT \(self.scrollView.contentSize)")
if let activeField = self.activeField {
print("ACTIVEFIELD FRAME ORIGIN \(activeField.frame.origin) ")
print("Active field is textfield tag is \(activeField.tag)")
// if (!aRect.contains(activeField.frame.origin)){
print("arect Does Not contains activeField")
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
print("TEXTFIELD FRAME ES \(activeField.frame)")
print(" SCROLLVIEW CONTENT \(self.scrollView.contentSize)")
//}
}
}
#objc func keyboardWillBeHidden(notification: NSNotification){
//Once keyboard disappears, restore original positions
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.activeField = nil
self.view.endEditing(true)
self.scrollView.isScrollEnabled = false
}
#objc func handleTap(_ sender: UITapGestureRecognizer) {
self.view.endEditing(true)
print("Tap")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height)
print(" SCROLLVIEW CONTENT AFTER SUBVIEWS \(self.scrollView.contentSize)")
}
/* // NOT WORKING BECAUSE OF UISCROLLVIEW IN PLACE, MUST USE UITAPGESTURE RECOGNIZER
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
self.activeField?.resignFirstResponder()
}
*/
}
I had the same problem. Apparently there is a change in getting the size of the keyboard. I changed UIKeyboardFrameBeginUserInfoKey to UIKeyboardFrameEndUserInfoKey and got it to work again.
Here is my exact code for moving the view when the textfield is pressed
#objc func keyboardWasShown(notification: NSNotification){
self.scrollView.isScrollEnabled = true
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
guard let kbHeight = keyboardSize?.height else{return}
aRect.size.height -= kbHeight
if let activeField = self.activeTextField {
if (!aRect.contains(activeField.frame.origin)){
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}

Move button when keyboard appears swift

In a UIViewController I have several text fields and a button is on the bottom of the UIViewController.
For the button, I have set a bottom constraint with a constant of 0.
Then I made an outlet from the bottom constraint to the UIViewController.
When I run my code, the button does not move upwards. I have seen suggestions on stackoverflow that I should add UIScrollView, but that means, I would have to delete all the objects on the UIViewController, put the UIScrollView and then put my objects on the UIVIewController again.
#IBOutlet weak var bottomConstraint: NSLayoutConstraint!
// When tapping outside of the keyboard, close the keyboard down
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
// Stop Editing on Return Key Tap. textField parameter refers to any textfield within the view
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// When keyboard is about to show assign the height of the keyboard to bottomConstraint.constant of our button so that it will move up
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
bottomConstraint.constant = keyboardSize.size.height
view.setNeedsLayout()
}
}
}
// When keyboard is hidden, move the button to the bottom of the view
func keyboardWillHide(notification: NSNotification) {
bottomConstraint.constant = 0.0
view.setNeedsLayout()
}
The typical way to address this would be to move the keyboard with code like this:
in ViewController class:
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
if view.frame.origin.y == 0{
let height = keyboardSize.height
self.view.frame.origin.y += height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
if view.frame.origin.y != 0 {
let height = keyboardSize.height
self.view.frame.origin.y -= height
}
}
}
in ViewDidLoad method:
NotificationCenter.default.addObserver(self, selector: Selector("keyboardWillShow:"), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: Selector("keyboardWillHide:"), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
Please Read This:
The way you are trying to solve your problem is not allowed. In the code above, if you change view to your button variable name, the button will shoot up and then fall back down. This is because Auto Layout and Programmatic layout do not work together, it is one or the other. The way you fix this is by programmatically creating that button (with CGRect), then using the code above to move only that button on keyboard press. (Do that by changing view to your button variable name.
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y == 0{
let height = keyboardSize.height
self.yourBtn.frame.origin.y += height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y != 0 {
let height = keyboardSize.height
self.yourBtn.frame.origin.y -= height
}
}
}
To programmatically create the button you would use code similar to this:
myButton.frame = CGRect(...)
Complimentary to Ryan's answer above, this can be done all with auto-layout and no need for frames and CGRect.
Swift 5
In your view, constrain your button as you normally would but add a reference to the constraint for modification when the keyboard hides/shows:
var bottomButtonConstraint = NSLayoutConstraint()
bottomButtonConstraint = yourButton.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -12)
bottomButtonConstraint.isActive = true
In your ViewController's viewDidLoad():
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)
Also in your ViewController:
#objc private func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.yourCustomView.bottomButtonConstraint.constant -= keyboardSize.height
}
}
#objc private func keyboardWillHide(notification: NSNotification) {
self.yourCustomView.bottomButtonConstraint.constant = -12
}
You need add(viewDidLoad) observers to call your functions:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardDidHideNotification, object: nil)
Consider using this pod: https://cocoapods.org/pods/IQKeyboardManager
In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.
import IQKeyboardManagerSwift
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.shared.enable = true
return true
}
}