如何在AppDelegate中隐藏和显示UIViewController按钮? - 斯威夫特

时间:2017-02-10 10:27:53

标签: ios swift uibutton

如何在swift中隐藏和显示AppDelegate文件中的UIViewController按钮? 对于exaple: role =" User" =>隐藏按钮; role ="管理员" =>查看按钮

代码:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
              withError error: Error!) {
         //var email = (String)()

        if (error == nil) {


        let givenName = user.profile.name
        let email  = user.profile.email

        let param=["UserName":givenName!,"Email":email!] as Dictionary<String,String>

        let request = NSMutableURLRequest(url: NSURL(string:"http://beta.json-generator.com/api/json/get/EJoC6gB_z")! as URL)

        let session = URLSession.shared
        request.httpMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try! JSONSerialization.data(withJSONObject: param, options: [])

        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }
            do{
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
                    print("Response: \(json)")
                    for user in json {
                        if let role = user["UserRole"] as? String{
                            print(role)

                            if role == "User"{


                                DispatchQueue.main.async (execute: { () -> Void in


                                let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle:nil)

                                let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController


                                let  pageNav = UINavigationController(  rootViewController : page )

                                let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate


                                appDelegate.window?.rootViewController=pageNav

                                  [self.vc.apps.isHidden]


                             })





                            } else if role == "NewUser"
                                {
                                    DispatchQueue.main.async (execute: { () -> Void in

                                    let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle :nil)

                                    let page=myStoryBoard.instantiateViewController(withIdentifier: "ApprovalUser") as! ApprovalUser

                                    let  pageNav = UINavigationController(rootViewController:page)

                                    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate


                                    appDelegate.window?.rootViewController=pageNav

                                })



                            }else if role == "Admin" {

                                    DispatchQueue.main.async (execute: { () -> Void in



                                    let  myStoryBoard:UIStoryboard = UIStoryboard(name:"Main",bundle : nil)

                                    let page=myStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

                                    let  pageNav = UINavigationController(rootViewController : page)

                                    let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate

                                    appDelegate.window?.rootViewController=pageNav

                                })


                            }
                        }
                    }
                    // if you want role of first object only then use
                    // print( json . first?["UserRole"])
                }
            } catch let parseError {
                print(parseError)
            }
        }

1 个答案:

答案 0 :(得分:0)

您可以使用UserDefaults或全局变量来执行此操作。从父视图控制器外部访问和修改UI元素是一种非常糟糕的做法。

我强烈推荐UserDefaults。在AppDelegate中,将其添加到您的代码中:

if role == "User"{
    UserDefaults.standard.set("User", forKey: "role")
    // ... the rest of your code (i.e.: appDelegate.window?.rootViewController=pageNav)
}

else if role == "NewUser"{
     UserDefaults.standard.set("NewUser", forKey: "role")
    // blah, blah, ... rest of your code goes here
} 
else if role == "Admin"{
     UserDefaults.standard.set("Admin", forKey: "role")
}

然后在ViewController的viewDidLoad()中:

 if UserDefaults.standard.value(forKey: "role") != nil{
      let role = UserDefaults.standard.value(forKey: "role") as? String ?? "User"
      if role == "User" || role == "NewUser" { 
          yourButton.isHidden = true 
          // the role of the user does not allow them to see the button
          }
      else if role == "Admin" { yourButton.isHidden = false }
 }
 else{
      yourButton.isHidden = true 
 }

在我看来,这是更好的方式,而不是从另一个类访问按钮。让我知道它是否有帮助!

说明:

基本上,您只需将role的值保存到UserDefaults(即基于捆绑ID的应用程序的本地内存),然后在viewDidLoad()内检索它。在那里,您可以根据具体情况检查角色并隐藏/显示按钮。

注意:这也处理了由于某种原因无法检索信息的情况,将用户视为普通用户&#34;用户&#34;。

编辑:

根据OP的要求,我添加了多个用户处理。当新用户登录时,只需从UserDefaults中删除这些值,然后调用整个函数。它看起来像这样:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
              withError error: Error!) {

         //var email = (String)()

         if UserDefaults.standard.value(forKey: "role") != nil{
         UserDefaults.standard.removeObject(forKey: "role")
         }

        if (error == nil) {
            //...
        }

}