NSNotfication.addObserver - Update to current Swift Syntax? - ios

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) {
}

Related

Problem with moving the view when the keyboard is open

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.
}
}

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 addObserver() issue

I'm trying to enable segue into a specific view upon opening a local notification by using NotificationCenter.addObserver(...)
My code is
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(LocalNotificationViewController.test), name: ???, object: nil)
}
With test method to perform the segue to ViewController with identifier NotificationView which I'm not sure what to put...
#objc func SomeNotificationAct(notification: NSNotification){
DispatchQueue.main.async() {
self.performSegue(withIdentifier: "NotificationView", sender: self)
}
}
My main question is how do I know the name of my local notification to put into the NotificationCenter.addObserver(...) method?
You will need to create extension for Notification name like,
extension Notification.Name {
static let hello1 = Notification.Name("HelloNotifcationName")
static let hello2 = Notification.Name("HelloNotifcationName2")
}
and use it like this,
NotificationCenter.default.addObserver(self, selector: #selector(setToHelloName1(notification:)), name: .hello1, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setToHelloName2(notfication:)), name: .hello2, object: nil)
You can find further reference or tutorial,here

Change UIScrollView Offset to top from another viewController in Swift 4

I have mainViewController and inside have scrollView and I have secondViewController I want to change scrollView offset to top from secondViewController when I want to try it with NSNotificationCenter gives me ;
: unrecognized selector sent to instance 0x7ff83e024200'
How can I fix it ?
My codes under below.
mainViewController
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: "gotop:", name: NSNotification.Name(rawValue: "gotop"), object: nil)
}
func gotop(){
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
}
secondViewController
#IBAction func goButton (sender : UIButton){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "gotop"), object: nil)
}
check your addObserver code, selector should have below signature
NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.goTop(notification:)), name: Notification.Name("gotop"), object: nil)
Method handler for received Notification:
func goTop(notification: Notification){
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
}
For posting notification
NotificationCenter.default.post(name: Notification.Name("gotop"), object: nil)
Remove Notification in denit
deinit {
NotificationCenter.default.removeObserver((self, name: Notification.Name("gotop"), object: nil)
}
I have used below code in my project to add notification :
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.gotop), name: NSNotification.Name(rawValue: "gotop"), object: nil)
Try if it works in your scenario.
the definition of your "goTop" func is wrong :
instead of
func gotop(){
//do your stuff
}
try this :
func gotop(notification : NSNotification){
//do your stuff
}
let me know if this solve your problem.

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