Problem with moving the view when the keyboard is open - ios

I have a problem with the moving of text input and button when the keyboard is open. I am using the following code
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func keyboardWillChange(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification {
view.frame.origin.y = -keyboardSize.height
} else {
view.frame.origin.y = 0
}
}
The problem occurs when I start typing in the text field, here are images before: https://imgur.com/a/cbQbJzW and after: https://imgur.com/a/f1Nakrs
I am sorry about the language it of files don't say anything spacial.
I want to know why this happens, is it possible to be because I am using CocoaPods - YoshikoTextField in the grey text field ?
Thank you!

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var backgroundScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
// Do any additional setup after loading the view, typically from a nib.
}
#objc func keyboardWillShow(notification:NSNotification) {
adjustingHeight(true, notification: notification)
}
#objc func keyboardWillHide(notification:NSNotification) {
adjustingHeight(false, notification: notification)
}
func adjustingHeight(_ isShow:Bool, notification:NSNotification) {
let userInfo = notification.userInfo!
let keyboardFrame = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let changeInHeight = (keyboardFrame.height + 20) * (isShow ? 1 : -1)
backgroundScrollView.contentInset.bottom += changeInHeight
backgroundScrollView.scrollIndicatorInsets.bottom += changeInHeight
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

Notification observer selector not called

I have this observer
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(GetUserID(_:)), name: Notification.Name("UserID"), object: nil)
}
and this selector function
#objc func GetUserID(_ notification: Notification){
let User = notification.object as? String
self.UserID = User
}
And I keep getting nil in UserID even though I am certain that when I get the notification it is not nil which makes me believe that the selector is not being called
You can get observer value by below method
let selectedIndex:[String: Int] = ["selectedIndex": 1]
//selectedindex = 0
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SelectedSegment"), object: nil, userInfo: selectedIndex)
NotificationCenter.default.addObserver(self, selector: #selector(self.changeSegmentControlIndex(notification:)), name: Notification.Name("SelectedSegment"), object: nil)
#objc func changeSegmentControlIndex(notification: Notification) {
if let selectedIndex = notification.userInfo?["selectedIndex"] as? Int {
// do something with your image
print(selectedIndex)
}
}

Notification Center not working. The observer is not being called

I am trying to call a function from another class in Swift and NotificationCenter is an option to do that so I started with the addObserver.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu), name: NSNotification.Name("callToggleSideMenu"), object: nil)
}
#objc func toggleSideMenu(){
if isMenuOpen {
sideContainer.constant = -260
} else {
sideContainer.constant = 0
}
}
And in the other class I have added the (post):
#objc func clickOnButton(button: UIButton) {
NotificationCenter.default.post(name: NSNotification.Name("callToggleSideMenu"), object: nil)
}
Everything seems ok but I do not know why it is not working. I have seen a lot of the same issue here in stackoverflow but no answer solved my issue.
Function definition is not correct. It should be :
#objc func toggleSideMenu(_ notification: Notification){
if isMenuOpen {
sideContainer.constant = -260
} else {
sideContainer.constant = 0
}
}
Call it using :
NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu(_:)), name: NSNotification.Name("callToggleSideMenu"), object: nil)

NotificationCenter - text transfer between views

I have this code:
MainViewControler.swift:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(showAlertMessage(notification:)), name: Notification.Name("NotificationAlertMessage"), object: errorMessage.self)
}
#objc func showAlertMessage(notification: NSNotification) {
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \(notification.title)")
}
AlertStruct.swift:
struct errorMessage{
var title: String?
var description: String?
}
Propierties.swift
func showError(){
NotificationCenter.default.post(name: Notification.Name("NotificationAlertMessage"), object: errorMessage(title: "tytuł", description: "description"))
}
override func viewDidLoad() {
super.viewDidLoad()
showError()
}
Propierties.swift is child in containerView MainViewControler.
I would like to display the function ShowAlertMessage in my MainViewControler with data sent from Propierties -> func showError ()
How to do it? My code does not want to compile / work correctly :(
Your code is almost correct...Just update below method
#objc func showAlertMessage(notification: NSNotification) {
let object = notification.object as! errorMessage
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \(object.title)")
}
try this, tested
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(showAlertMessage(notification:)), name: Notification.Name("NotificationAlertMessage"), object: nil)
NotificationCenter.default.post(name: Notification.Name("NotificationAlertMessage"), object: nil, userInfo: ["object": ErrorMessage(title: "tytuł", description: "description")])
}
#objc func showAlertMessage(notification: NSNotification) {
if let errorMessage = notification.userInfo?["object"] as? ErrorMessage {
print("\(errorMessage.title), \(errorMessage.description)")
}
}

NSNotfication.addObserver - Update to current Swift Syntax?

Currently following a tutorial, however, some of the syntax is outdated. Basically the code should show and hide the user keyboard. I get some syntax errors with the addObserver method and Swift wants me to use key path instead, however, if i use the auto 'fix-it' i get even more errors. Can anyone help me out with this? Thanks!
NSNotification.addObserver(self, selector: #selector(keyboardwillShow), name: .UIKeyboardWillShow, nil)
NSNotification.addObserver(self, selector: #selector(keyboardwillHide), name: .UIKeyboardWillHide, nil)
func keyboardwillShow(_notification:NSNotification) {
keyboard = (_notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
UIView.animate(withDuration: 0.4) {
self.scrolledView.frame.size.height = self.scrollViewHeight - self.keyboard.height
}
}
func keyboardwillHide(_notification:NSNotification) {
UIView.animate(withDuration: 0.5) {
self.scrolledView.frame.size.height = self.view.frame.height
}
}
I get the debug message: "Incorrect argument labels in call(have _selector:name, expected _forKeyPath:options:context"
Your function has argument, That is missing when you add it in observer
And you have to use NotificationCenter.default.addObserver not NotificationCenter.addObserver
let selectorForKeyBoardWillShow: Selector = #selector(ViewController.keyboardWillShow(_:))
let selectorForKeyBoardWillHide: Selector = #selector(ViewController.keyboardWillHide(_:))
// MARK: - Functions
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillShow, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillHide, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// MARK: Keyboard Observer
func keyboardWillShow(_ notification: Notification) {
}
func keyboardWillHide(_ notification: Notification) {
}

Swift 3 NSNotificationCenter Keyboardwillshow/hide

I have a piece of code that worked in Swift 2 and I tried using Xcode to update the code to the newest version and I fixed everything except two issues.
I have this code :
let loginvc: LoginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
That pairs along with this:
func keyboardWillShow(notification: NSNotification) {
constraint.constant = -100
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
func keyboardWillHide(notification: NSNotification) {
constraint.constant = 25
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
On the first part I now get an error saying
Type 'LoginViewController' has no member 'keyboardWillShow/Hide'
I don't understand why it is not seeing the method underneath.
Does anybody know a solution to this issue?
Check out the updated Swift Programming Language book. Pages 1027 and 1028 are what you're looking for. It should be something like this:
func keyboardWillHide(_ notification: NSNotification) {…
Notice the additional underscore above. Also:
#selector(LoginViewController.keyboardWillHide(_:))
You also might need to add #objc(keyboardWillHideWithNotification:) to your class.
On Swift 4.2, addObserver name for NSNotificationCenter changed as well:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardDidHideNotification, object: nil)
Use that code that's work on swift3
You can use your ViewController (e.g, loginvc) to add notification
let loginvc : LoginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
NotificationCenter.default.addObserver(self,
selector: #selector(loginvc.keyboardWillShow(notification:)),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(loginvc.keyboardWillHide(notification:)),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)
Then add keyboard hide and show method
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
print("Show")
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
print("Hide")
}
}
NSNotificationCenter have things alter for get show keyboard:
NotificationCenter.default.addObserver(self, selector: #selector(NovaVisitaVC.abreTeclado(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(NovaVisitaVC.abreTeclado(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

Resources