首页 > 解决方案 > calling a class shared function from action

问题描述

I have a file called SocialLogin.swift inside that I have a class with some functions see below. What I am trying to do however is have the FirstViewController.swift set up a button which has an action.

The "action" is to call SocialLogin.shared.checkLogin() However everytime I run it seems to crash giving me no real understanding on why it does this.

Where when I run the same code but instead of sending it to a shared class, i send it to a local function it works fine.

 let buttonIcon = UIImage(systemName: "person.circle")

 let rightBarButton = UIBarButtonItem(title: "Person", style: UIBarButtonItem.Style.done, target: self, action: #selector(SocialLogin.shared.checkLogin(_:)))
         rightBarButton.image = buttonIcon

self.tabBarController?.navigationItem.rightBarButtonItem = rightBarButton

This is the SocialLogin.swift file

class SocialLogin {
    static let shared = SocialLogin()

    @objc func checkLogin(_ sender:UIBarButtonItem!){
        print("checking now")
    }

    @objc func loginFacebook(){
        print("test")
    }
}

标签: iosswift

解决方案


Just set proper target!

let rightBarButton = UIBarButtonItem(title: "Person", style: UIBarButtonItem.Style.done, target: SocialLogin.shared, action: #selector(SocialLogin.checkLogin(_:)))

推荐阅读